這題陣列數字加一時要進位。
LeetCode 題目連結
https://leetcode.com/problems/plus-one/
題目
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1] Output: [4,3,2,2] Explanation: The array represents the integer 4321.
Accept 作法
Runtime: 1 ms
Memory: 39.4 MB
Java 程式碼
class Solution { public int[] plusOne(int[] digits) { boolean isAllZero = false; for(int i = digits.length -1;i>=0;i--){ int sum = digits[i] +1; if(sum <= 9){ digits[i] +=1; isAllZero = false; break; }else{ digits[i] =0; isAllZero = true; } } if(isAllZero){ int[] newResult = new int[digits.length+1]; for(int i = 0;i<digits.length+1;i++){ if(i == 0){ newResult[i] = 1; }else{ newResult[i] = 0; } } return newResult; } return digits; } }
更多 LeetCode 相關資源
複習程式面試書籍
除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備。
需要的話可以看看,寫得很仔細。
需要的話可以看看,寫得很仔細。
沒有留言:
張貼留言