个人记录-LeetCode 66. Plus One

来源:互联网 发布:小米开源软件 编辑:程序博客网 时间:2024/06/07 02:06

问题:
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.

这个问题比较简单,就是注意进位即可。

代码示例:

public class Solution {    public int[] plusOne(int[] digits) {        if (digits == null || digits.length < 1) {            return digits;        }        for (int i = digits.length - 1; i >= 0; --i) {            //9+1,需要进位            if (digits[i] == 9) {                digits[i] = 0;            } else {                //如果中间某一位+1后,不需要进位,那么结束                digits[i] += 1;                break;            }        }        //如果最高位变为0,说明进位了,重新分配空间即可        if (digits[0] != 0) {            return digits;        } else {            int[] rst = new int[digits.length+1];            rst[0] = 1;            System.arraycopy(digits, 0, rst, 1, digits.length);            return rst;        }    }}
0 0
原创粉丝点击