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


给定1个数组,完成加1的操作。本题和大整数加法非常类似。 逻辑比较简单,直接实现就可以了
当前位= num[i]%10
进位= num[i]/10



实现代码:



public class Solution {
    public int[] PlusOne(int[] digits) {
        if (digits == null || digits.Length == 0){
		return null;
    	}
    	
    	
    	var len = digits.Length;
    	var c = digits[len-1] == 9 ? 1: 0;
    	
    	digits[len-1] = digits[len-1] == 9 ? 0 : digits[len-1] + 1;
    	
    	for(var i = len - 2;i >= 0 ; i--){
    		var s = digits[i] + c ;
    		c = s / 10;
    		digits[i] = s % 10;
    	}
    	
    	if(c > 0){
    		var arr = new List<int>{1};
    		arr.AddRange(digits);
    		return arr.ToArray();
    	}
    	
    	return digits;
    }
}


你可能感兴趣的:(Leet -- Plus One)