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.

給定一個非負整數組成的非空數組,在該數的基礎上加一,返回一個新的數組。

最高位數字存放在數組的首位, 數組中每個元素只存儲一個數字。

你可以假設除了整數 0 之外,這個整數不會以零開頭。

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.

【思路】

我英文實在不行 ,後來看別人的語意才了解。

給一包含非數整數的陣列,其中每一個值代表該位數的值,對這個陣列加1。

範例:
19 = [1,9] , 19+1 = 20 = [2,0]。

【解法】

因為題目他說他只會加一

我就用死方法判斷 如果他最後一個元素是9 再去作後續邏輯判斷

所以如果不是9 那就單純加1回傳就好了

☆JAVA

class Solution {
    public int[] plusOne(int[] digits) {
        int[] result = null;
        boolean status = true;
        if(null != digits){
            for(int i = digits.length-1 ; i >=0 ; i--){
                if(status && (digits[i])+1 == 10){
                    digits[i] = 0;
                    status = true;
                }else{
                    digits[i] = (digits[i])+1;
                    status = false;
                    break;
                }
            }

                #這段用來處理如果 第零位進位  Ex: {9} +1 = {1,0}
            if(status){
                int[] resultNew = new int[1 + digits.length];
                resultNew[0] = 1;
                for(int i = 1; i < resultNew.length; i++) {
                    resultNew[i] = digits[i-1];
                }
                digits = resultNew;
            }
            result = digits;
        }      
        return result;
    }
}

results matching ""

    No results matching ""