Plus One

来源:互联网 发布:ubuntu和优麒麟 编辑:程序博客网 时间:2024/06/06 13:57

题目地址:https://leetcode.com/problems/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.

题目说只有非负数,这个题目的难度将下降不少。题目本身没啥难度,关键是处理好进位即可:

input: {9,9,9,9}output: {1,0,0,0,0}input: {0,0,9,9,9,9}output: {0,1,0,0,0,0}

处理好这两种情况就没啥难的了:

public class PlusOne {    public static int[] plusOne(int[] digits) {        for (int i = digits.length - 1; i >= 0; i--) {            boolean carry = false;            int val = digits[i] + 1;            if (val < 10) {                digits[i] = val;                break;            }            else {                digits[i] = val - 10;                if (i == 0) {                    int[] r = new int[digits.length + 1];                    int[] c = {1};                    System.arraycopy(c, 0, r, 0, c.length);                    System.arraycopy(digits, 0, r, c.length, digits.length);                    return r;                }                continue;            }        }        return digits;    }    public static void main(String[] args) {        int[] digits = {0, 0, 9,9,9,9,9};        System.out.println(Arrays.toString(digits));        System.out.println(Arrays.toString(plusOne(digits)));    }}

感觉第二种测试案例不太合理,虽说不为错,但是至少得出结果得把前面高位的0去掉。

0 0
原创粉丝点击