(Java)LeetCode-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.


这道题题意刚开始没看明白。。原来是用数组表示一个数,然后把这个数加一,再返回一个数组。

这道题蛮简单,遍历一遍就可以了,只不过要考虑如果最后存在进位,需要增加数组的长度。代码如下:



	
	public static void main(String[] args){
		Solution sol = new Solution();
		int[] digits = {9,9,9};
		int[] res = sol.plusOne(digits);
		for(int i : res){
			System.out.print(i);
		}
    }
	
	public int[] plusOne(int[] digits) {
		
		int c = 1;
		int len = digits.length;
		int temp = 0;
		for(int i = len-1 ; i>=0 ; i--){
			temp = digits[i] + c;
			digits[i] = temp % 10;
			c = temp / 10;
		}
		if(c == 0)
			return digits;
		else{
			int[] res = new int[len+1];
			res[0] = 1;
			for(int i = 0; i < len; i++){
				res[i+1] = digits[i];
			}
			return res;
		}
    }
}



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