LeetCode算法题-Easy-Math(66)

66、Plus One

题目:Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

意思是:
输入一个int数组,最后一个元素+1,与数字加法一样,若最后一个元素为9,+1则该元素为0,前面一个元素进1。
比如:输入[1,2,9] ,输出[1,3,0]

分析下思路:
从最后一位遍历起,最后一位+1如果不超过9,则直接+1后重新赋值然后return,如果超过9,则赋值为0,继续下一个循环,如果有比如[9,9]的情况,则循环过后,重新创建数组,第0位赋值1就OK了。

class Solution {
    public int[] plusOne(int[] digits) {
       int n = digits.length;
       for(int i=n-1; i>=0; i--) {
           if(digits[i] < 9) {
                digits[i]++;
                return digits;
            }
       
           digits[i] = 0;
       }
    
       int[] newNumber = new int [n+1];
       newNumber[0] = 1;
    
       return newNumber;
    }
    
}

你可能感兴趣的:(LeetCode算法题-Easy-Math(66))