Posted on

Description

Submission

class Solution {
public:
    int numSteps(string s) {
        int ret = 0;
        for(; s != "1"; ret++) {
            if(s.back() == '1') {
                // add 1
                auto iter = prev(s.end());
                for(; iter != s.begin() && *iter != '0'; --iter) {
                    *iter = '0';
                }
                
                if(iter == s.begin() && *iter == '1') {
                    *iter = '0';
                    s.insert(s.begin(), '1');
                } else {
                    *iter = '1';
                }
                
            } else {
                // divide by 2
                s.pop_back();
            }
        }
        
        return ret;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *