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.

答案

class Solution {
    public int[] plusOne(int[] digits) {
        int sum, carry = 1;
        int[] ans = new int[digits.length + 1];
        for(int i = digits.length - 1; i >= 0; i--) {
            sum = digits[i] + carry;
            ans[i + 1] = sum % 10;
            digits[i] = sum % 10;
            carry = (sum >= 10) ? 1:0;
            if(carry == 1 && i == 0)
                ans[0] = 1;
        }
        return (carry == 1)?ans:digits;
    }
}
class Solution {
    public int[] plusOne(int[] digits) {
        
        for(int i = digits.length - 1; i >= 0; i--) {
            if(digits[i] == 9) {
                digits[i] = 0;
                continue;
            }
            digits[i]++;
            return digits;
        }
        int[] ans = new int[digits.length + 1];
        ans[0] = 1;
        return ans;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問(wèn)題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,935評(píng)論 0 33
  • 原題是: Given a non-negative integer represented as a non-em...
    小雙2510閱讀 159評(píng)論 0 0
  • 你在嗎,在我的身旁 你能聽(tīng)見(jiàn)嗎,我傳遞的情 你在嗎,在我的城市 你能看見(jiàn)嗎,我放的煙花 你在嗎,在我的國(guó)家 你能感...
    甜宋兒閱讀 166評(píng)論 0 2
  • 我外公,外婆是90后,閑不住的他們?nèi)砸サ乩锔苫睿趧诘乃麄冏尯筝吚餂](méi)懶惰的人,是他們讓我懂得勤勞會(huì)使生活變得有滋...
    a06b93caddc4閱讀 416評(píng)論 5 2
  • 1、其實(shí)我們也可以喚她睡不著小姐??傊褪窃诿恳粋€(gè)夜深人靜里有時(shí)安靜有時(shí)煩躁的和黑夜對(duì)抗。用一切可以想到的方法。到...
    不睡小姐閱讀 329評(píng)論 0 1

友情鏈接更多精彩內(nèi)容