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的那個數組。

題意理解比較難。
比如給定的整型數組爲{9,9,9,9}. 那麼應該返回{1,0,0,0,}

只要注意進位就好,設定一個int值保存進位。



    public int[] plusOne(int[] digits) {
        int carry=1;//假設加的那個1就是一個進位,好計算。
        for(int i=digits.length-1;i>=0;i--){
            if((digits[i]+=carry)==10) {
                digits[i]=0  ;
                carry=1;
            }
            else carry=0;
        }
        if (carry==1){
            int[] result=new int[digits.length+1];
            result[0]=1;
            for(int i=0;i<digits.length;i++){
                result[i+1]=digits[i];
            }
            return result;
        }
        else return digits;
    }
發佈了88 篇原創文章 · 獲贊 5 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章