摘要:題目詳情題目的意思是,給你一個用數(shù)組表示的一個非負(fù)整數(shù)。你需要返回這個整數(shù)加后,所對應(yīng)的數(shù)組。解法一主要需要關(guān)注的點(diǎn)就在于,當(dāng)末尾數(shù)字為的時候的進(jìn)位情況。如果不需要進(jìn)位了,則代表循環(huán)可以結(jié)束了。
題目詳情
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.
題目的意思是,給你一個用int數(shù)組表示的一個非負(fù)整數(shù)。你需要返回這個整數(shù)加1后,所對應(yīng)的int數(shù)組。解法一
主要需要關(guān)注的點(diǎn)就在于,當(dāng)末尾數(shù)字為9的時候的進(jìn)位情況。
如果不需要進(jìn)位了,則代表循環(huán)可以結(jié)束了。此時直接返回輸入的digits數(shù)組
如果數(shù)組的所有元素都為9,則需要在最前面補(bǔ)一位1,我們應(yīng)該意識到剩下的位都為0,不需要通過循環(huán)賦值,只需要把數(shù)組的第一位賦值為1就可以,剩下的元素自然為0
public int[] plusOne(int[] digits){ int carry = 1; for(int i=digits.length-1;i>=0;i--){ if(digits[i] + carry == 10){ digits[i] = 0; carry = 1; }else{ digits[i] = digits[i] + carry; return digits; } } int[] res = new int[digits.length+1]; res[0] = 1; return res; }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://m.hztianpu.com/yun/67109.html
摘要:題目要求一個非負(fù)整數(shù)被表示為一個數(shù)組,數(shù)組中每一個元素代表該整數(shù)的一個位。數(shù)組的下標(biāo)越小,代表的位數(shù)越高?,F(xiàn)在對該數(shù)組做加一運(yùn)算,請返回結(jié)果數(shù)組。 題目要求:一個非負(fù)整數(shù)被表示為一個數(shù)組,數(shù)組中每一個元素代表該整數(shù)的一個位。數(shù)組的下標(biāo)越小,代表的位數(shù)越高?,F(xiàn)在對該數(shù)組做加一運(yùn)算,請返回結(jié)果數(shù)組。 /** * @author rale * * Given a non-negativ...
摘要:不過這里有個小技巧,因?yàn)槲覀冎灰樱圆挥猛耆M加法的所有規(guī)則一個數(shù)如果不是,那加以后不會對其他位產(chǎn)生影響。 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...
Problem 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. Example Given [1,2...
Problem Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer. You may assume the integer do not contain any leading zero, except the number 0 i...
摘要:自己沒事刷的一些的題目,若有更好的解法,希望能夠一起探討項(xiàng)目地址 自己沒事刷的一些LeetCode的題目,若有更好的解法,希望能夠一起探討 Number Problem Solution Difficulty 204 Count Primes JavaScript Easy 202 Happy Number JavaScript Easy 190 Reverse Bi...
閱讀 4067·2021-09-27 13:35
閱讀 1182·2021-09-24 09:48
閱讀 2969·2021-09-22 15:42
閱讀 2404·2021-09-22 15:28
閱讀 3212·2019-08-30 15:43
閱讀 2680·2019-08-30 13:52
閱讀 3037·2019-08-29 12:48
閱讀 1541·2019-08-26 13:55