66. Plus One
原题链接:https://leetcode.com/problems/plus-one/description/
这道题目自己花了二十分钟解出来了,看了下讨论区别人家的答案之后,感觉自己脑子上装的就是一坨屎:
import java.util.Arrays;
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(Arrays.toString(s.plusOne(new int[]{1, 2, 3, 4})));
System.out.println(Arrays.toString(s.plusOne(new int[]{1, 2, 3, 4, 5})));
System.out.println(Arrays.toString(s.plusOne(new int[]{4, 3, 2, 2})));
System.out.println(Arrays.toString(s.plusOne(new int[]{1, 9, 9, 9})));
System.out.println(Arrays.toString(s.plusOne(new int[]{9, 9, 9, 9})));
}
/**
* 我的思路
*
* @param digits
* @return
*/
public int[] plusOne(int[] digits) {
boolean carry = true;
for (int i = digits.length - 1; i >= 0; i--) {
if (carry) {
if (digits[i] + 1 >= 10) {
carry = true;
digits[i] = digits[i] + 1 - 10;
} else {
carry = false;
digits[i] = digits[i] + 1;
}
}
}
if (carry) {
int[] res = new int[digits.length + 1];
res[0] = 1;
for (int i = 0; i < digits.length; i++) {
res[i + 1] = digits[i];
}
return res;
} else {
return digits;
}
}
/**
* 官方讨论区的答案,看完之后真的发现自己很吃鲸😲
*
* @param digits
* @return
*/
public int[] plusOne2(int[] digits) {
for (int i = digits.length - 1; i >= 0; i--) {
if (digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
int[] res = new int[digits.length + 1];
res[0] = 1;
return res;
}
}