leetcode : Plus One 基本功

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.

 

算法基本功, 进位的处理。  

遇到进位处理的,要想到求模,求余

 

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

    }
    
}

  

posted @ 2017-02-28 15:56  notesbuddy  阅读(161)  评论(0编辑  收藏  举报