Plus One

来源:互联网 发布:thinkphp sqlserver 编辑:程序博客网 时间:2024/04/28 21:22

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.

题意:一个整数按位存储于一个int数组中,排列顺序为:最高位在array[0] ,最低位在[n-1],例如:98,存储为:array[0]=9; array[1]=8;

解题思路,从数组的最后一位开始加1,需要考虑进位,如果到[0]位之后仍然有进位存在,需要新开一个长度为(n.length + 1)的数组,拷贝原来的数组。

代码如下:

public class Solution {    public int[] plusOne(int[] digits) {        if(digits==null||digits.length==0) return null;        int carry = 1;        int sum = 0;        int len = digits.length;        for(int i=len-1;i>=0;i--){            sum = digits[i]+carry;            digits[i] = sum%10;            carry = sum/10;        }        if(carry>0){            int[] a = new int[len+1];            a[0] = carry;            for(int i=0;i<len;i++){                a[i+1] = digits[i];            }            return a;        }        return digits;            }}


0 0
原创粉丝点击