Algorithm-Arrays-2

1.问题–Add One to Number

Given a non-negative number represented as an array of digits,

add 1 to the number ( increment the number represented by the digits ).

The digits are stored such that the most significant digit is at the head of the list.

Example:

If the vector has [1, 2, 3]

the returned vector should be [1, 2, 4]

as 123 + 1 = 124.

NOTE: Certain things are intentionally left unclear in this question which you should practice asking the interviewer.
For example, for this problem, following are some good questions to ask :
Q : Can the input have 0’s before the most significant digit. Or in other words, is 0 1 2 3 a valid input?
A : For the purpose of this question, YES
Q : Can the output have 0’s before the most significant digit? Or in other words, is 0 1 2 4 a valid output?
A : For the purpose of this question, NO. Even if the input has zeroes before the most significant digit.
即:给出一个非负值,以数组的方式表示该值的每一位;且每位数值是以最高位在前的顺序排列的。

2.思路

  1. 首先将数组的值转换为数值是不现实的
    因为,假设数组的长度为几十位,则会超过给定类型存储数值上限。
  2. 逐位分析时,加1时将会有2种情况,其一是结果没有进位的情况、其二是结果有进位的情况

3.代码及解答

public class Solution {
    public ArrayList<Integer> plusOne(ArrayList<Integer> a) {
        ArrayList<Integer> result = new ArrayList<>();
        int carry = 1;
        for(int i=a.size()-1; i>=0; i--){
            int num = (a.get(i)+carry)%10;
            carry = (a.get(i)+carry) / 10;
            a.set(i,num);
        }
        if(carry==1)
            result.add(1);
        for(int ele: a){
            if(result.size()==0 && ele==0)
                continue;
                result.add(ele);
        }
        return result;
    }
}

你可能感兴趣的:(算法,array,数组操作,进位)