I tried to solve 266. ‘Plus One’.

Problem

66. Plus One

problem

My idea

I use shift flag. if digit > 9, shift flag is true and high-order digit + 1

Correct Solution

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {        
        bool shift = false;
        digits[digits.size()-1]++;
        for(int i=digits.size()-1;i>=0;i--){
           if(shift){
              digits[i]++;
              shift = false;
           } 
           if(digits[i] > 9){
               shift = true;
               digits[i] = 0;
           }
        }
        if(shift){
            digits.insert(digits.begin(),1);
        }
        return digits;
    }
};

My wrong idea

In first, I think convert arrary to unsinged long long. and deconvert. but it happens rounding? invalid result.

Input: [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
Output: [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,4,0,9]
Expected: [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4] 
class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        long long unsigned num = 0;
        vector<int> res;
        for(int i=0;i<digits.size();i++){
            num += digits[i] * pow(10,digits.size()-1-i);
        }
        num++;
        while(num > 0){
            int pop = num % 10;
            num /= 10;
            res.push_back(pop);                
        }
        std::reverse(res.begin(), res.end());
        return res;
    }
};