`

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.

这道题目和Add Binary 这道题,还有Add Two Numbers 这道题目属于同一类型的题目。主要的问题要维护一个进位carry,根据题目的要求,不管是二进制还是十进制,如果有进位,carry就为1。最后要检查最后一位是否有进位,如果有进位要重新设定数组的长度,来保存进位。代码如下:
public class Solution {
    public int[] plusOne(int[] digits) {
        int carry = 0;
        for(int i = digits.length - 1; i >= 0; i--) {
            if(i == digits.length - 1) digits[i] ++;
            int tem = digits[i] + carry;
            if(tem > 9) {
                carry = 1;
            } else {
                carry = 0;
            }
            digits[i] = tem % 10;
        }
        if(carry == 1) {
            int[] result = new int[digits.length + 1];
            result[0] = 1;
            return result;
        }
        return digits;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics