1404. Number of Steps to Reduce a Number in Binary Representation to One #271
-
|
Topics: Given the binary representation of an integer as a string
It is guaranteed that you can always reach one for all test cases. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We are given a binary string
We need to determine how many steps it takes to achieve this. Observations
ApproachSimulate the process step by step:
Let's implement this solution in PHP: 1404. Number of Steps to Reduce a Number in Binary Representation to One <?php
/**
* @param String $s
* @return Integer
*/
function numSteps($s) {
$ans = 0;
// All the trailing 0s can be popped by 1 step.
while ($s[strlen($s) - 1] == '0') {
$s = substr($s, 0, -1);
++$ans;
}
if ($s == "1")
return $ans;
// `s` is now odd, so add 1 to `s` and cost 1 step.
++$ans;
// All the 1s will become 0s and can be popped by 1 step.
// All the 0s will become 1s and can be popped by 2 steps (adding 1 then
// dividing by 2).
for ($i = 0; $i < strlen($s); $i++) {
$ans += $s[$i] == '1' ? 1 : 2;
}
return $ans;
}
// Example usage:
$s1 = "1101";
$s2 = "10";
$s3 = s = "1";
echo numSteps($s1) . "\n"; // Output: 6
echo numSteps($s2) . "\n"; // Output: 1
echo numSteps($s3) . "\n"; // Output: 0
?>Explanation:
Complexity Analysis
Example WalkthroughInput:
|
Beta Was this translation helpful? Give feedback.
We are given a binary string
sthat represents a number. The goal is to reduce this number to1by performing the following operations:2.1to it.We need to determine how many steps it takes to achieve this.
Observations
0and odd if its last digit is1.2is equivalent to removing its last digit (s = substr($s, 0, -1)).1to a binary number can sometimes cause a carry that affects the preceding digits.Approach
Simulate the process step by step: