DEV Community

Karleb
Karleb

Posted on

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

https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/description/?envType=daily-question&envId=2024-05-29

var numSteps = function(s) {

    let carry = 0
    let steps = 0;

    for (let i = s.length - 1; i > 0; i--) {
        if (s.charAt(i) - '0' + carry == 1) {
            carry = 1
            steps += 2
        } else {
            steps++
        }
    }

    return steps + carry
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)