【LeetCode-面試演算法經典-Java實現】【066-Plus One(加一)】

來源:互聯網
上載者:User

標籤: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(加一)】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.