February 15, 2024

Viiisit [LeetCode] - 66. Plus One

#php#javascript#ruby

keep learning, keep coding!

Problem - Plus One

You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0’s.

Increment the large integer by one and return the resulting array of digits.

翻譯蒟蒻

給定一個整數陣列,其中每個元素表示整數的一位數字,並對最後一位數字加一,回傳新的陣列。


要考慮到進位的可能性。



Solution - JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* @param {number[]} digits
* @return {number[]}
*/
var plusOne = function(digits) {
let carry = 1;
for (let i = digits.length - 1; i >= 0; i--) {
let sum = digits[i] + carry;
if (sum > 9) {
digits[i] = sum % 10;
carry = 1;
} else {
digits[i] = sum;
carry = 0;
}
}
if (carry === 1) {
digits.unshift(1);
}
return digits;
};

Solution - Ruby

1
2
3
4
5
6
7
8
9
10
def plus_one(digits)
carry = 1
(digits.length - 1).downto(0) do |i|
sum = digits[i] + carry
digits[i] = sum % 10
carry = sum / 10
end
digits.unshift(1) if carry == 1
digits
end

Solution - PHP

1
2
3
4
5
6
7
8
9
10
11
12
function plusOne($digits) {
$carry = 1;
for ($i = count($digits) - 1; $i >= 0; $i--) {
$sum = $digits[$i] + $carry;
$digits[$i] = $sum % 10;
$carry = (int)($sum / 10);
}
if ($carry) {
array_unshift($digits, $carry);
}
return $digits;
}

PHP 方法筆記

LeetCode 傳送門 - Plus One