Plus One

来源:互联网 发布:点位图软件 brd 编辑:程序博客网 时间:2024/04/30 19:43

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.

题意:一个非负整数按位存储于一个数组中,排列顺序为:最高位在array[0] ,最低位在[n-1],例如:29,存储为:array[0]=2; array[1]=9;
解题思路,对数组的最后一位加1操作,需要考虑进位,如果到[0]位之后仍然有进位存在,需要新开一个长度为(n.length + 1)的数组,拷贝原来的数组。

public class Solution {    public int[] plusOne(int[] digits) {        boolean flag = false;//进位标志                for (int i = digits.length - 1; i >= 0 ; i--) {        digits[i]++;//最后一位加1if (digits[i]>9) {flag = true;digits[i] = 0;}else {return digits;}}        if (flag == true) {//进位操作,把旧数组拷贝到新数组中int[] newDigits = new int[digits.length+1];//新数组长度多一位newDigits[0] = 1;for (int i = 1; i < newDigits.length; i++) {newDigits[i] = digits[i-1];}return newDigits;}else {return digits;}    }}


0 0
原创粉丝点击