Leet Code OJ 66. Plus One [Difficulty: Easy]
生活随笔
收集整理的這篇文章主要介紹了
Leet Code OJ 66. Plus One [Difficulty: Easy]
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目:
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.
翻譯:
給定一個(gè)非負(fù)數(shù),它是有數(shù)字的數(shù)組組成,把這個(gè)非負(fù)數(shù)+1。
這個(gè)非負(fù)數(shù)的存儲(chǔ)方式,是把最高有效位數(shù)字放到列表的前面。
分析:
首先考慮的是進(jìn)位,當(dāng)最后一位是“9”的時(shí)候,會(huì)發(fā)生向前進(jìn)位。
再考慮一種特殊情況”999”,執(zhí)行加一操作后,數(shù)組的長(zhǎng)度變了,這個(gè)時(shí)候需要重新創(chuàng)建一個(gè)新數(shù)組。筆者采用一個(gè)標(biāo)志位needAdd,用來記錄循環(huán)完成時(shí),是否還有未進(jìn)的位。
代碼:
public class Solution {public int[] plusOne(int[] digits) {if(digits.length==0){return new int[]{1};}int index=digits.length-1;boolean needAdd=false;while(index>=0){digits[index]++;if(digits[index]<10){needAdd=false;break;}digits[index]-=10;index--;needAdd=true;}if(needAdd){int[] digitsNew=new int[digits.length+1];for(int i=0;i<digits.length;i++){digitsNew[i+1]=digits[i];}digitsNew[0]=1;return digitsNew;}return digits;} }總結(jié)
以上是生活随笔為你收集整理的Leet Code OJ 66. Plus One [Difficulty: Easy]的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 58. Len
- 下一篇: Leet Code OJ 268. Mi