Topic:
Given a decimal number, each bit is represented by an array, and the result of adding one is required to return
Ideas:
From the end of the array to the head processing, use a overflow flag to determine if overflow, and if overflow requires a new array
Attention:
arraycopy (Object src, int srcpos, object dest, int destpos, int length)
Import Java.util.Arrays;
/** * Plus One * * Given a number represented as an array of digits, plus one to the number.
*/public class S66 {public static void main (string[] args) {int[] digits = {9,9,9};//int[] digits = {0};
System.out.println (arrays.tostring (PlusOne (digits)));
} public static int[] PlusOne (int[] digits) {int i = digits.length-1; int overflow = 0; Used to indicate whether the overflow//from the end of the head plus while (I >= 0) {if (Digits[i]+1 > 9) {//Add more than 9 cases digits[i] =
0;
overflow = 1;
i--;
}else{//Add up to less than 10 of the situation digits[i] = digits[i]+1;
return digits; }}//This is a situation where the current number of bits is not sufficient, you must open the array,//handle first if (Overflow > 0) {int[] Newdigit
s = new int[digits.length+1];
System.arraycopy (digits, 0, newdigits, 1, digits.length);
Newdigits[0] = 1;
Newdigits[1] = 0;
return newdigits;
} return digits; }
}
public class Solution {public
int[] PlusOne (int[] digits) {
int[] ret = new Int[digits.length];
int i = digits.length-1;
int c = 0; Carry
while (I >= 0) {
int val = digits[i];
if (i==digits.length-1) { //rightmost
val + = c + 1;
} else if (C > 0) { //carry
val + = c
;
} if (Val > 9) {
ret[i] = 0;
c = 1;
} else{
Ret[i] = val;
c = 0;
}
i--;
}
if (c = = 1) {
int[] copy = new int[digits.length+1];
System.arraycopy (copy, 1, ret, 0, ret.length);
Copy[0] = 1;
return copy;
} else{
return ret;}}}