1404. Number of Steps to Reduce a Number in Binary Representation to One Medium

@problem@discussion
#String#Bit Manipulation



1/**
2 * [1404] Number of Steps to Reduce a Number in Binary Representation to One
3 *
4 * Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules:
5 * 
6 * 	
7 * 	If the current number is even, you have to divide it by 2.
8 * 	
9 * 	
10 * 	If the current number is odd, you have to add 1 to it.
11 * 	
12 * 
13 * It is guaranteed that you can always reach one for all test cases.
14 *  
15 * Example 1:
16 * 
17 * Input: s = "1101"
18 * Output: 6
19 * Explanation: "1101" corressponds to number 13 in their decimal representation.
20 * Step 1) 13 is odd, add 1 and obtain 14. 
21 * Step 2) 14 is even, divide by 2 and obtain 7.
22 * Step 3) 7 is odd, add 1 and obtain 8.
23 * Step 4) 8 is even, divide by 2 and obtain 4.  
24 * Step 5) 4 is even, divide by 2 and obtain 2. 
25 * Step 6) 2 is even, divide by 2 and obtain 1.  
26 * 
27 * Example 2:
28 * 
29 * Input: s = "10"
30 * Output: 1
31 * Explanation: "10" corressponds to number 2 in their decimal representation.
32 * Step 1) 2 is even, divide by 2 and obtain 1.  
33 * 
34 * Example 3:
35 * 
36 * Input: s = "1"
37 * Output: 0
38 * 
39 *  
40 * Constraints:
41 * 
42 * 	1 <= s.length <= 500
43 * 	s consists of characters '0' or '1'
44 * 	s[0] == '1'
45 * 
46 */
47pub struct Solution {}
48
49// problem: https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/
50// discuss: https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/discuss/?currentPage=1&orderBy=most_votes&query=
51
52// submission codes start here
53
54impl Solution {
55    pub fn num_steps(s: String) -> i32 {
56        0
57    }
58}
59
60// submission codes end
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn test_1404() {
68    }
69}
70


Back
© 2025 bowen.ge All Rights Reserved.