Number of Steps to Reduce a Number in Binary Representation to One LeetCode solution in C++
1class Solution {2public:3int numSteps(string s) {4int n = 0;5bool carry = false;6int steps = 0;7if (s == "1") return 0;8while (s.length() > 0) {9int i = s.length() - 1;10if (carry) {11if (s[i] == '1') {12carry = true;13s[i] = '0';14} else {15s[i] = '1';16carry = false;17}18}19if (s[i] == '0') {20s.pop_back();21steps++;22} else {23carry = true;24s.pop_back();25steps += 2;26}27if (s == "1") {28if (carry) steps++;29break;30}31}32return steps;33}34};