LeetCode Plus One

来源:互联网 发布:java tar.gz循环解压 编辑:程序博客网 时间:2024/06/15 18:41

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.

题意:一个整数表示的是一个大整数,最高位放在下标为0的位置,将这个数加1后求结果

思路:从最低位加1,如果有进位,继续计算,没有,就返回 

public class Solution {    public int[] plusOne(int[] digits) {        int i = digits.length - 1;        int carry = 0;                while (i >= 0) {            if (digits[i] + 1 > 9) {                carry = 1;                digits[i] = 0;                i--;            } else {                digits[i]++;                return digits;            }        }                if (carry != 0) {            int[] newdigits = new int[digits.length + 1];            System.arraycopy(digits, 0, newdigits, 1, digits.length);            newdigits[0] = 1;            return newdigits;        }                return digits;    }}


0 0
原创粉丝点击