题目:
解答:
1 class Solution { 2 public: 3 int numSteps(string s) 4 { 5 int idx = s.size() - 1; 6 int ans = 0; 7 while(idx > 0) 8 { 9 //第一位最后肯定剩1,不另计算 10 if(s[idx] == ‘0‘) 11 { 12 ans++; 13 idx--; 14 } 15 else 16 { 17 ans++;//进位的+1 18 while(idx >= 0 && s[idx] == ‘1‘) 19 { 20 //进位后,连续的1产生连续的0 21 ans++; 22 idx--; 23 } 24 if(idx > 0) 25 { 26 s[idx] = ‘1‘; 27 } 28 } 29 } 30 return ans; 31 } 32 };
原文:https://www.cnblogs.com/ocpc/p/12826248.html