2571. Minimum Operations to Reduce an Integer to 0 Medium

@problem@discussion
#Dynamic Programming#Greedy#Bit Manipulation



1/**
2 * [2571] Minimum Operations to Reduce an Integer to 0
3 *
4 * You are given a positive integer n, you can do the following operation any number of times:
5 * 
6 * 	Add or subtract a power of 2 from n.
7 * 
8 * Return the minimum number of operations to make n equal to 0.
9 * A number x is power of 2 if x == 2^i where i >= 0.
10 *  
11 * <strong class="example">Example 1:
12 * 
13 * Input: n = 39
14 * Output: 3
15 * Explanation: We can do the following operations:
16 * - Add 2^0 = 1 to n, so now n = 40.
17 * - Subtract 2^3 = 8 from n, so now n = 32.
18 * - Subtract 2^5 = 32 from n, so now n = 0.
19 * It can be shown that 3 is the minimum number of operations we need to make n equal to 0.
20 * 
21 * <strong class="example">Example 2:
22 * 
23 * Input: n = 54
24 * Output: 3
25 * Explanation: We can do the following operations:
26 * - Add 2^1 = 2 to n, so now n = 56.
27 * - Add 2^3 = 8 to n, so now n = 64.
28 * - Subtract 2^6 = 64 from n, so now n = 0.
29 * So the minimum number of operations is 3.
30 * 
31 *  
32 * Constraints:
33 * 
34 * 	1 <= n <= 10^5
35 * 
36 */
37pub struct Solution {}
38
39// problem: https://leetcode.com/problems/minimum-operations-to-reduce-an-integer-to-0/
40// discuss: https://leetcode.com/problems/minimum-operations-to-reduce-an-integer-to-0/discuss/?currentPage=1&orderBy=most_votes&query=
41
42// submission codes start here
43
44impl Solution {
45    pub fn min_operations(n: i32) -> i32 {
46        0
47    }
48}
49
50// submission codes end
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn test_2571() {
58    }
59}
60


Back
© 2025 bowen.ge All Rights Reserved.