TypechoJoeTheme

IT技术分享

统计

[LeetCode 66] Plus One [Java]

2018-02-16
/
0 评论
/
733 阅读
/
正在检测是否收录...
02/16

1. Description

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.

2. Example

digits = [9,9,9]
return [1,0,0,0]

3.Code

import java.util.Arrays;

public class LeetCode0066 {
    public int[] plusOne(int[] digits) {

        if (digits == null || digits.length == 0) {
            return digits;
        }

        int carry = 1;
        for (int i = digits.length - 1; i >= 0; i--) {
            carry += digits[i];
            digits[i] = carry % 10;
            carry /= 10;
        }

        if (carry == 0) {
            return digits;
        }

        else {
            int[] tmp = new int[digits.length + 1];
            tmp[0] = carry;
            System.arraycopy(digits, 0, tmp, 1, digits.length);
            return tmp;
        }
    }

    public static void main(String[] args) {
        LeetCode0066 leetcode = new LeetCode0066();
        int[] digits = new int[] { 9, 9, 9 };
        System.out.println(Arrays.toString(leetcode.plusOne(digits)));
    }
}
Math
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1444/(转载时请注明本文出处及文章链接)