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.

题目不难,只要当数为9999这种类型时,开辟一个新数组即可。

代码如下:

public class Solution {
    public int[] plusOne(int[] digits) {
        int carry=0,n=digits.length;
        for(int i=n-1;i>=0;i--){
        	carry=(digits[i]+1)/10;
        	digits[i]=(digits[i]+1)%10;
        	if(carry==0)
        		break;
        }
        if(carry==1){
        	int[] newdigits=new int[n+1];
        	newdigits[0]=1;
        	for(int i=1;i<=n;i++){
        		newdigits[i]=0;
        	}
        	return newdigits;
        }
        return digits;
    }
}


你可能感兴趣的:(java,LeetCode,Math)