iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 3
0
Software Development

LeetCode刷題日記系列 第 5

【Day 5】#66 - 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.

解析

此題要求將一非空陣列所代表的數值加1,然後再回傳該數字所代表的陣列。
且除了數值為0外(即陣列為[0]),陣列開頭不得為0。

解法

class Solution {
     public int[] plusOne(int[] digits) {

        int n = digits.length;
        for (int i = n - 1; i >= 0; i--) {
            if (digits[i] < 9) {
                digits[i]++;
                return digits;
            }
            digits[i] = 0;
        }
        int[] newArr = new int[n + 1];
        newArr[0] = 1;
        return newArr;
     }
}

心得

此題說難不難,說簡單也不簡單,就看有沒有想到解法。


希望透過記錄解題的過程,可以對於資料結構及演算法等有更深一層的想法。
如有需訂正的地方歡迎告知,若有更好的解法也歡迎留言,謝謝。


上一篇
【Day 4】#53 - Maximum Subarray
下一篇
【Day 6】#11 - Container With Most Water
系列文
LeetCode刷題日記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言