66.Plus One
2218 ワード
タイトル:
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 ist the head of the list.
リンク: http://leetcode.com/problems/plus-one/
クイズ:
Time Coplexity-O(n),Space Coplexity-O(n)。
テスト:
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 ist the head of the list.
リンク: http://leetcode.com/problems/plus-one/
クイズ:
Time Coplexity-O(n),Space Coplexity-O(n)。
public class Solution {
public int[] plusOne(int[] digits) {
int carry = 1;
for(int i = digits.length - 1; i >= 0; i --){
int curValue = digits[i];
digits[i] = (curValue + carry) % 10;
carry = (curValue + carry) >= 10 ? 1 : 0;
}
if(carry == 1){
int[] result = new int[digits.length + 1];
result[0] = 1;
for(int i = 1; i < result.length; i ++){
result[i] = digits[i - 1];
}
return result;
} else
return digits;
}
}
テスト: