More:【目錄】LeetCode Java實現html
https://leetcode.com/problems/plus-one/java
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.git
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:post
Input: [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123.
Example 2:ui
Input: [4,3,2,1] Output: [4,3,2,2] Explanation: The array represents the integer 4321.
讀完題,首先要考慮到的是:1. 負數狀況;2. 溢出狀況;3.數字的順序 123是[1,2,3]存放仍是[3,2,1]存放。code
本題比較簡單,只要根據當前位的數字是否小於9來判斷是否進位。詳見代碼。htm
public int[] plusOne(int[] digits) { if(digits==null) return digits; for(int i=digits.length-1; i>=0; i--){ if(digits[i] < 9){ digits[i]++; return digits; } digits[i]=0; } int[] newDigits=new int[digits.length+1]; newDigits[0]=1; //其他位的數都是0,如:999+1=1000 return newDigits; }
這道題本身一開始想的是使用遞歸函數,傳入當前的index,後面參考別人的代碼才發現,其實只要遍歷數組就能夠了。blog
若是最高位還進位的話,那麼說明最高位是1,其他位都是0。其他位不用從舊的數組賦值到新的數組中了。
More:【目錄】LeetCode Java實現