LeetCode 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.
题意是 输入一个数,这个数被表示成一个数组,数组就是这个数的从高到低位。然后对这个数+1;返回结果。
解法是 分情况讨论,没有进位的话,就直接输出就行了,如果有进位,而且数组溢出了,就返回一个新的数组。
1 public class Solution { 2 public int[] plusOne(int[] digits) { 3 int oneplus=0; 4 for (int i = digits.length-1; i >=0; i--) { 5 if (digits[i]<9) { 6 digits[i]++; 7 oneplus=0; 8 break; 9 }else { 10 oneplus=1; 11 digits[i]=0; 12 } 13 } 14 15 if (oneplus == 1) { 16 int[] res = new int[digits.length+1]; 17 res[0]=1; 18 for (int i = 1; i < res.length; i++) { 19 res[i]=digits[i-1]; 20 } 21 return res; 22 } 23 24 return digits; 25 } 26 }