LeetCode OJ:Plus One (加1)
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
这题的题目写的比较简单,就是让你把代表的数加上1就可以,一开始尽然还没看懂题目,真是糗,代码如下:
1 vector<int> plusOne(vector<int>& digits) { 2 reverse(digits.begin(), digits.end()); 3 int sz = digits.size(); 4 int flag = 0; 5 for(int i = 0; i< sz; ++i){ 6 int val = digits[i] + flag; 7 digits[i] %= val; 8 flag = val/10; 9 } 10 if(flag != 10) 11 digits.push_back(flag); 12 reverse(digits.begin(), digits.end()); 13 return digits; 14 }
下面是用java写的版本,跟上面还是不太一样的:
1 public class Solution { 2 public int[] plusOne(int[] digits) { 3 int carry = 1; 4 for(int i = digits.length-1; i >= 0; --i){ 5 int val = digits[i] + carry; 6 carry = 0; 7 digits[i] = val%10; 8 carry = val/10; 9 } 10 if(carry > 0){ 11 int [] ret = new int[digits.length + 1]; 12 ret[0] = carry; 13 System.arraycopy(digits, 0, ret, 1, digits.length); 14 return ret; 15 } 16 return digits; 17 } 18 }