码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] Plus One

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

标签:style   blog   http   java   color   os   

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

标签:style   blog   http   java   color   os   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!