首页 > 代码库 > 66. Plus One

66. 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.

Solution 1: 

思路:刚开始想的是用for来遍历,但是这样会出很多不必要的操作。直接用while来判断是否有carry,carry为1就继续从右往左加1,carry为0就跳出循环。注意全为9的情况,因此要在while条件里面加m的范围来限制。跳出循环后再检查carry的情况,为1就再create new array把特殊情况输出,为0就输出digits。

public class Solution {    public int[] plusOne(int[] digits) {        int carry=1;        int m=digits.length-1;        while(carry!=0&&m>=0)        {            if(digits[m]<9)            {                digits[m]++;                carry=0;            }            else            {                digits[m]=0;                carry=1;            }            m--;        }        if(carry==1)        {            int[] res=new int[digits.length+1];            res[0]=1;            return res;        }        return digits;            }}

66. Plus One