66. Plus One

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

Hide Company Tags

一刷
題解:
Time Complexity - O(n), Space Complexity - O(n)。

public class Solution {
    public int[] plusOne(int[] digits) {
        int added = 1;
        for(int i=digits.length-1; i>=0; i--){
            int cur = digits[i] + added;
            added = cur/10;
            cur = cur%10;
            digits[i] = cur;
        }
        
        if(added == 1){
            int[] temp = new int [digits.length + 1];
            temp[0] = 1;
            for(int i=0; i<digits.length; i++){
                temp[i+1] = digits[i];
            }
            return temp;
        }
        else return digits;
    }
}

還有一種簡潔的方法:

public class Solution {
    public int[] plusOne(int[] digits) {
        int i = digits.length -1;
        while(i>=0){
            if(digits[i] == 9){
                digits[i] = 0;
                i--;
            }
            else {
                digits[i] +=1;
                return digits;
            }
        }
        
        int[] temp = new int [digits.length+1];
        temp[0] = 1;
        return temp;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,766評論 0 33
  • 今天晚班回來,洗好澡,給他刮痧,躺在床上看微信公眾號。小女兒跑過來躺在我身邊抱著我,要說會話。問我明天幾點下班,想...
    芳老頭閱讀 278評論 0 0