[leetcode]66.Plus One

來源:互聯網
上載者:User

標籤:except   ++   car   nts   兩種   hat   single   nat   res   

題目

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.

解法一思路

思路很簡單,如果數組的最後一個元素小於9,最後一個元素直接加1,然後返回修改後的數組即可。如果數組的最後一個元素等於9,就判斷它之前的元素是否等於9,如果等於,則繼續往前找,直到找到最靠前的9的位置pos,此時又分為兩種情況,如果pos不為0,那麼說明數組的長度不需要變化,直接pos-1位置的元素加一即可,如果pos為0,那麼建立個長度加1的數組,且將第一個元素設定為1即可(int數組預設初始值為0)。

代碼
class Solution {    public int[] plusOne(int[] digits) {        int pos = digits.length - 1;        int length = pos;        int[] des = new int[length+2];        if(digits[pos] < 9) {            ++digits[pos];            return digits;        } else {            digits[pos] = 0;            while(pos-1 >= 0 && digits[pos-1] == 9 && pos-1 >= 0) {                digits[pos-1] = 0;                pos--;            }            if(pos > 0){                digits[pos-1]++;                return digits;            }            else{                des[0] = 1;                return des;            }                          }    }}

以上的代碼是自己寫的,不夠優雅,以下的代碼思路相同,但比較優雅

class Solution {    public int[] plusOne(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;    }}
解法二思路

可能用carry來記載有沒有進位。此種思路與[leetcode]67.Add Binary這道題思路很相似。

代碼
class Solution {    public int[] plusOne(int[] digits) {        if (digits.length == 0) return digits;        int carry = 1, n = digits.length;        for (int i = digits.length - 1; i >= 0; --i) {            int sum = digits[i] + carry;            digits[i] = sum % 10;            carry = sum / 10;            if (carry == 0) return digits;        }        int[] res = new int[n + 1];        res[0] = 1;        return res;    }}

[leetcode]66.Plus One

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.