
Sponsored
Sponsored
This approach involves simulating the reduction steps performed directly on the binary number string. We traverse the binary string backwards, simulating each step based on whether the current number is odd or even. Additionally, whenever we encounter a carry after incrementing an odd number, we propagate the carry to handle the necessary binary addition.
Time Complexity: O(n), where n is the length of the string s.
Space Complexity: O(1), only a constant amount of extra space is used.
1class Solution {
2 public int numSteps(String s) {
3 int steps = 0, carry = 0;
4 for (int i = s.length() - 1; i > 0; i--) {
5 if ((s.charAt(i) - '0' + carry) % 2 == 0) {
6 steps += 1;
7 } else {
8 steps += 2;
9 carry = 1;
10 }
11 }
12 return steps + carry;
13 }
14
15 public static void main(String[] args) {
16 Solution solution = new Solution();
17 System.out.println(solution.numSteps("1101")); // Output: 6
18 }
19}This Java implementation uses similar logic as in C++ and C#. Character manipulation is used to decode binary and manage the carry as needed for calculation of steps.
Convert the binary representation to a decimal integer, then simulate the operations using intuitive arithmetic operations. This approach avoids character-level string manipulations.
Time Complexity: O(n) for initial conversion, O(log m) for operations (where m is the integer value).
Space Complexity: O(1), after input conversion.
This implementation converts the binary input to a decimal integer using Python's base conversion. Then the function reduces the number using arithmetic operations analogous to the original rules (dividing when even or incrementing plus dividing when odd).