../ Competitive Programming
-rw-r--r--aguang965 B1 min read

Leet Code Daily 2024-05-24 - Number of Steps to Reduce a Number in Binary Representation to One

Solution

Simulation

Code

c++
class Solution {
public:
    int numSteps(string s) {
        int ans = 0;
        while (s != "1") {
            if (s[s.size() - 1] == '0') {
                s.pop_back();
                ans++;
            } else {
                for (int i = s.size() - 1; i >= 0; i--) {
                    if (s[i] == '1') {
                        s[i] = '0';
                        if (i == 0) {
                            s = '1' + s;
                            break;
                        }
                    } else {
                        s[i] = '1';
                        break;
                    }
                }
                ans++;
            }
        }
        return ans;
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window