標籤:div font pos append word bre 計算 代碼 ++
【066-Plus One(加一)】
【LeetCode-面試演算法經典-Java實現】【全部題目檔案夾索引】
原題
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
題目大意
給定一個用數組表示的一個數。對它進行加一操作。
每個數位都儲存在數組的一個位置上。數組下標從大到小表示數位從低位到高位。
解題思路
直接求解,設定一個進位標誌carry,初值為1。表示加1,從最低位開始tmp = a[x] + carry。
a[x] = tmp%10。carry = tmp/10,假設carry不為0對下一位再進行操作,直到全部的數位處理完或者carray為0就退出,假設最後還有carray不為0說明整個數組要擴充一個數位。
代碼實現
演算法實作類別
public class Solution { public int[] plusOne(int[] digits) { int carry = 1; // 進位標誌,下一位來的進位標誌 int tmp; for (int i = digits.length - 1; i >= 0; i--) { tmp = digits[i]; digits[i] = (tmp + carry) % 10; // 計算當前位的新值 carry = (tmp + carry) / 10; // 計算新的進位 if (carry == 0) { // 沒有進位了就能夠退出了 break; } } if (carry == 1) { // 最後另一個進位 int[] result = new int[digits.length + 1]; System.arraycopy(digits, 0, result, 1, digits.length); result[0] = carry;; return result; } else { return digits; } }}
評測結果
點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的表單中查看完整圖片。
特別說明
歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47203315】
【LeetCode-面試演算法經典-Java實現】【066-Plus One(加一)】