66. Plus One
class Solution {
/**
* @param Integer[] $digits
* @return Integer[]
*/
function plusOne($digits) {
$key = array_key_last($digits);
$result = [];
while($key > -1) {
if ($digits[$key] < 9) {
++$digits[$key];
return $digits;
}
$digits[$key] = 0;
--$key;
if($key < 0) {
return [1, ...$digits];
}
}
}
}
從最後一個數開始 +1, 遇到 9 則該位置寫 0。如第一位是 9, 除了寫 0 外,要與 [1] 合併成新陣列
Last updated