首页 > 其他 > 详细

[leetcode] Plus One

时间:2014-07-10 09:58:23      阅读:387      评论:0      收藏:0      [点我收藏+]

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.

https://oj.leetcode.com/problems/plus-one/

 

思路:大数计算的思想,注意carry的处理。如果最高位进位需要重新分配数组空间。

bubuko.com,布布扣
import java.util.Arrays;

public class Solution {
    public int[] plusOne(int[] digits) {
        if (digits == null || digits.length == 0)
            return digits;
        int n = digits.length;
        int i;
        int c = 1;
        for (i = n - 1; i >= 0; i--) {
            if (c == 0)
                break;
            digits[i] += c;
            if (digits[i] > 9) {
                digits[i] -= 10;
                c = 1;
            } else
                c = 0;

        }
        if (c == 1) {
            int[] newDigits = new int[n + 1];
            newDigits[0] = 1;

            for (i = 0; i < n; i++)
                newDigits[i + 1] = digits[i];

            return newDigits;
        } else
            return digits;

    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new Solution().plusOne(new int[] { 1, 9, 9 })));

    }

}
View Code

 

 

[leetcode] Plus One,布布扣,bubuko.com

[leetcode] Plus One

原文:http://www.cnblogs.com/jdflyfly/p/3812487.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!