LeetCode - Algorithms - 66. Plus One

Problem

66. Plus One

Java

1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public int[] plusOne(int[] digits) {
final int N = digits.length;
List<Integer> list = new ArrayList<Integer>();
boolean carry = false;
int tmp = digits[N - 1] + 1;
if (tmp < 10) {
list.add(tmp);
} else {
list.add(tmp % 10);
carry = true;
}
if (N >= 2) {
for (int i = N - 2; i >= 0; i--) {
tmp = digits[i];
if (carry)
tmp++;
if (tmp < 10) {
carry = false;
list.add(tmp);
} else {
carry = true;
list.add(tmp % 10);
}
}
}
if (carry)
list.add(1);

final int LEN = list.size();
int[] a = new int[LEN];
for (int i = 0; i < LEN; i++) {
a[LEN - i - 1] = list.get(i).intValue();
}
return a;
}
}

Submission Detail

  • 109 / 109 test cases passed.
  • Runtime: 1 ms, faster than 17.94% of Java online submissions for Plus One.
  • Memory Usage: 39.9 MB, less than 5.08% of Java online submissions for Plus One.

2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public int[] plusOne(int[] digits) {
final int N = digits.length;
List<Integer> list = new ArrayList<Integer>();
boolean carry = false;
int tmp = digits[N - 1] + 1;
if (tmp < 10) {
list.add(tmp);
} else {
list.add(tmp - 10);
carry = true;
}
for (int i = N - 2; i >= 0; i--) {
tmp = digits[i];
if (carry)
tmp++;
if (tmp < 10) {
carry = false;
list.add(tmp);
} else {
carry = true;
list.add(tmp - 10);
}
}
if (carry)
list.add(1);

final int LEN = list.size();
int[] a = new int[LEN];
for (int i = 0; i < LEN; i++) {
a[LEN - i - 1] = list.get(i).intValue();
}
return a;
}
}

Submission Detail

  • 109 / 109 test cases passed.
  • Runtime: 1 ms, faster than 17.94% of Java online submissions for Plus One.
  • Memory Usage: 38.4 MB, less than 20.96% of Java online submissions for Plus One.

3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public int[] plusOne(int[] digits) {
final int N = digits.length;
int[] a2 = new int[N];
boolean carry = false;
int tmp = digits[N - 1] + 1;
if (tmp < 10) {
a2[N - 1] = (tmp);
} else {
a2[N - 1] = tmp - 10;
carry = true;
}
for (int i = N - 2; i >= 0; i--) {
tmp = digits[i];
if (carry)
tmp++;
if (tmp < 10) {
carry = false;
a2[i] = tmp;
} else {
carry = true;
a2[i] = tmp - 10;
}
}
if (carry) {
int[] a1 = new int[N + 1];
a1[0] = 1;
System.arraycopy(a2, 0, a1, 1, N);
return a1;
} else
return a2;
}
}

Submission Detail

  • 109 / 109 test cases passed.
  • Runtime: 0 ms, faster than 100.00% of Java online submissions for Plus One.
  • Memory Usage: 39.6 MB, less than 8.37% of Java online submissions for Plus One.