-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddOneObj.java
More file actions
50 lines (45 loc) · 1.36 KB
/
Copy pathAddOneObj.java
File metadata and controls
50 lines (45 loc) · 1.36 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
package one_day_test;
import java.util.Arrays;
/**
* 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
*
* 最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。
*
* 你可以假设除了整数 0 之外,这个整数不会以零开头。
*
* 示例 1:
*
* 输入: [1,2,3]
* 输出: [1,2,4]
* 解释: 输入数组表示数字 123。
* 示例 2:
*
* 输入: [4,3,2,1]
* 输出: [4,3,2,2]
* 解释: 输入数组表示数字 4321。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/plus-one
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class AddOneObj {
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;
}
public static void main(String[] args) {
AddOneObj addOneObj = new AddOneObj();
// int[] digits = new int[]{1, 2, 3};
int[] digits = new int[]{1, 2, 9};
int[] res = addOneObj.plusOne(digits);
System.out.println(Arrays.toString(res));
}
}