plus one

Q:

Given a number represented as an array of digits, plus one to the number.

A:

很简单,练练手,看看怎么才能写的漂亮

class Solution {
 public:
  vector<int> plusOne(vector<int> &digits) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    int pos = digits.size() - 1;
    while (pos >= 0) {
      if (digits[pos] < 0 || digits[pos] >= 10) {
        return vector<int>();
      }   

      if (digits[pos] + 1 == 10) {
        digits[pos] = 0;
      } else {
        digits[pos] += 1;
        return digits;
      }   
      --pos;
    }   
    vector<int> res;
    res.push_back(1);
    res.insert(res.end(), digits.begin(), digits.end());
    return res;
  }
};

 

posted @ 2013-06-14 13:01  dmthinker  阅读(107)  评论(0)    收藏  举报