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.
Subscribe to see which companies asked this question
题目大意就是用一个int数组来模拟十进制数加1的计算,需要注意的地方就是溢出的情况.
1 public class Solution { 2 public int[] plusOne(int[] digits) { 3 int len = digits.length; 4 digits[len-1]++; 5 boolean flag = false;//是否溢出 6 for(int i=len -1; i>=0;i--){ 7 if(digits[i] >= 10) { 8 if(i != 0){ 9 digits[i-1]++; 10 }else{ 11 flag =true; 12 } 13 digits[i] -= 10; 14 } 15 } 16 if(flag == true){ 17 int[] res = new int[len+1]; 18 res[0] = 1; 19 for(int i = 0;i<len;i++){ 20 res[i+1] = digits[i]; 21 } 22 return res; 23 }else{ 24 return digits; 25 } 26 27 } 28 }