leetcode66- Plus One- easy
阿新 • • 發佈:2017-12-03
return itself eas git dig self tor clas 實現
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
1.善用/ %,用c記錄,踏踏實實做就好。問一下能不能直接改原數組,不能的話就再開個list輔助也行。
2.觀察規律,最後大一格的話只可能發生在輸入全是9的情況,而且加後的結果就是新位1後面全是0。所以你可以直接先假設不是極端情況一直加上去,如果遇到不是9的時候就可以直接把改後的原數組返回了。如果最後還是沒有返回的話就說明遇到極端情況,直接開一個新的長一點的第一個位改1即可。
1.基礎版模擬法實現
class Solution { public int[] plusOne(int[] digits) { List<Integer> list = new ArrayList<>(); int[] result;int idx = digits.length - 1; int c = 1; while (idx >= 0) { int digit = digits[idx] + c; list.add(digit % 10); c = digit / 10; idx--; } result = new int[digits.length + c]; int start = c; result[0] = c;for (int i = start; i < result.length; i++) { result[i] = list.get(list.size() - (i - start) - 1); } return result; } }
2.觀察規律實現
public int[] plusOne(int[] digits) { int n = digits.length; for(int i=n-1; i>=0; i--) { if(digits[i] < 9) { digits[i]++; return digits; } digits[i] = 0; } int[] newNumber = new int [n+1]; newNumber[0] = 1; return newNumber; }
leetcode66- Plus One- easy