LeetCode(29)-Plus One
題目:
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.
思路:
題意是用一個數組來表示一個非負的整數,范圍是0~9的數字,模擬一個加法的加一操作 判斷是否進位,如果是9,加1就是10,置為0,然後進位。 如果超除了界限,重新設置一個數組,第一位是1,後面是0 -
代碼:
public class Solution {
public int[] plusOne(int[] digits) {
int carries = 1;
for(int i = digits.length-1; i>=0 && carries > 0; i--){ // fast break when carries equals zero
int sum = digits[i] + 1;
digits[i] = sum % 10;
carries = sum / 10;
}
if(carries == 0)
return digits;
int[] rst = new int[digits.length+1];
rst[0] = 1;
for(int i=1; i< rst.length; i++){
rst[i] = 0;
}
return rst;
}
}