Saturday, December 29, 2012

[LeetCode] Plus One 解题报告

Given a number represented as an array of digits, plus one to the number.
» Solve this problem

[解题思路]
加位与进位。模拟。

[Code]
1:  vector<int> plusOne(vector<int> &digits) {  
2:      // Start typing your C/C++ solution below  
3:      // DO NOT write int main() function  
4:      int cary=1, sum =0;  
5:      vector<int> result(digits.size(),0);  
6:      for(int i = digits.size()-1; i>=0; i--)  
7:      {        
8:        sum = cary+digits[i];  
9:        cary = sum/10;  
10:        result[i] = sum%10;  
11:      }  
12:      if(cary >0)  
13:      {  
14:        result.insert(result.begin(), cary);  
15:      }  
16:      return result;  
17:    }  


No comments:

Post a Comment