Leetcode Problem Solving Note-plusone

Source: Internet
Author: User

Topic content:

Given an int array, which represents a different bit of a non-negative number, the result is returned as an array of int after adding 1 to the figure.

Individual Solution 1:

1. The array is now converted to int followed by 1 and then into an array, so it is possible to ignore the overflow so that it cannot be passed

Individual Solution 2:

This solution super trouble oneself also do not go down, feel for array operation part is not very familiar with:

1. First define a arralist as the result set (because it is indefinite, regardless of the boundary problem), then judge each of the digits above, if plus 1 equals 10 digits[i]=0 and carry =1

2. Put the calculated results into ArrayList, and then the results in the ArrayList in reverse order output to the result array.

3. The sense of space complexity is very high.

Individual Solution 3:

1. This is again a brute force solution, the data of the fixed length is very annoying.

2. Operate the digits first, then assign the result according to the Carry

3. It is important to note that the boundary problem is related to rounding.

Code:

public static int[] PlusOne (int[] digits) {
int len = digits.length;
int carry = 1;
for (int i= len-1; i>=0;-I.) {
if (digits[i]==9&&carry==1) {
digits[i]=0;
Carry=1;
}else{
Digits[i] +=carry;
carry=0;
}
}
if (carry==0) {
Int[] result = new Int[len];
for (int i=0; i<len;i++) {
Result[i]=digits[i];
}
return result;
}else{
Int[] result = new Int[len+1];
Result[0]=carry;
for (int i=1; i<len+1;i++) {
RESULT[I]=DIGITS[I-1];
}
return result;
}

}

It feels good.

Leetcode Problem Solving Note-plusone

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.