Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitd7633a1

Browse files
plus one
1 parentf1feae8 commitd7633a1

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

‎EASY/src/easy/PlusOne.java

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
packageeasy;
2+
3+
importutils.CommonUtils;
4+
5+
/**66. Plus One QuestionEditorial Solution My Submissions
6+
Total Accepted: 115402
7+
Total Submissions: 328650
8+
Difficulty: Easy
9+
Given a non-negative number represented as an array of digits, plus one to the number.
10+
11+
The digits are stored such that the most significant digit is at the head of the list.*/
12+
publicclassPlusOne {
13+
//also looked at Discuss, basically the same idea as mine, just their code is more concise.
14+
15+
publicint[]plusOne(int[]digits) {
16+
booleancarry =false;
17+
intlen =digits.length;
18+
int[]temp =digits;
19+
//process the last digit at first, to get carry value
20+
if(digits[len-1] +1 ==10) {
21+
carry =true;
22+
temp[len-1] =0;
23+
}
24+
else {
25+
temp[len-1] +=1;
26+
returntemp;
27+
}
28+
29+
//start from the second last element
30+
for(inti =len-2;i >=0;i--){
31+
if(carry &&temp[i] +1 ==10){
32+
temp[i] =0;
33+
carry =true;
34+
}elseif(carry) {
35+
temp[i] +=1;
36+
carry =false;
37+
}
38+
}
39+
if(carry &&temp[0] ==0) {
40+
int[]res =newint[len+1];
41+
res[0] =1;
42+
//all the rest of the numbers should all be zeroes, so we don't need to copy from the original array
43+
returnres;
44+
}
45+
returntemp;
46+
}
47+
48+
publicstaticvoidmain(String...strings){
49+
PlusOnetest =newPlusOne();
50+
// int[] digits = new int[]{9,9,9,9};
51+
// int[] digits = new int[]{8,9,9,9};
52+
int[]digits =newint[]{2,4,9,3,9};
53+
int[]res =test.plusOne(digits);
54+
CommonUtils.printArray(res);
55+
}
56+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp