[2019.11.26] algorithm learning record - plus one

Algorithms - plus one


Given a non-negative integer nonempty array of integers represented, on the basis of the number plus one.

Most significant digit stored in the first array, each element of the array stores only a single digit.

You may assume that in addition to the integer 0, the integer does not begin with a zero.

Example 1:

Input: [1,2,3]
Output: [2,4]
Explanation: numeral 123 denotes the input array.
Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: input array represents a number 4321.

Source: stay button (LeetCode)

A thought:

class Solution {
    public int[] plusOne(int[] digits) {
        String cache ="";
        String sb = "";
        for(int i =0;i<digits.length;i++){
            sb= sb + digits[i];
        }
        long before = Long.parseLong(sb);
        long after = before + 1;
        String result=String.valueOf(after);
        int[] list = new int[result.length()];
        for(int i=0; i<result.length();i++){
            list[i] = Integer.parseInt(String.valueOf(result.charAt(i)));
        }
        return list;        
    }
}
    

The method of the idea is to turn into a string array, then into digital, the number by one and then translated into strings, after obtaining an empty array length, each bit string is converted into digital fill.
However, this methodProblemsYes, if the input array is too long, there will be an overflow problem when converting to digital.


Thinking two:

class Solution {
    public int[] plusOne(int[] digits) {
        for(int i = digits.length-1; i>=0; i--){
            digits[i]++;
            digits[i] = digits[i]%10;
            if(digits[i]!=0){
                return digits;
            }
            }
            digits = new int[digits.length+1];
            digits[0] = 1;
            return digits;
        }
    }

This method is applicable to any array (0 is not the first), processed through from right to left, the main consider three cases:

  1. 123 (general case);
  2. 199 (into the required position);
  3. 999 (not only carry an array of length will be changed).

Notes
must when you declare an arrayDeclare the array lengthThe following is a statement often used an array of methods:

String[] aArray = new String[5];

String[] bArray = {"a","b","c", "d", "e"};

String[] cArray = new String[]{"a","b","c","d","e"};
Published 17 original articles · won praise 0 · Views 343

Guess you like

Origin blog.csdn.net/cletitia/article/details/103261658