imajinyun /
leetcode-php
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace leetcode; |
||
| 6 | |||
| 7 | class AddToArrayFormOfInteger |
||
| 8 | { |
||
| 9 | public static function addToArrayForm(array $nums, int $k): array |
||
| 10 | { |
||
| 11 | if (empty($nums) || $k < 0) { |
||
| 12 | return []; |
||
| 13 | } |
||
| 14 | [$ans, $n] = [[], count($nums)]; |
||
| 15 | for ($i = $n - 1; $i >= 0; $i--) { |
||
| 16 | $sum = $nums[$i] + $k % 10; |
||
| 17 | $k = (int) ($k / 10); |
||
| 18 | if ($sum >= 10) { |
||
| 19 | $k++; |
||
| 20 | $sum -= 10; |
||
| 21 | } |
||
| 22 | $ans[] = (int) $sum; |
||
| 23 | } |
||
| 24 | for (; $k > 0; $k = (int) ($k /= 10)) { |
||
| 25 | $ans[] = $k % 10; |
||
| 26 | } |
||
| 27 | |||
| 28 | return array_reverse($ans); |
||
| 29 | } |
||
| 30 | |||
| 31 | public static function addToArrayForm2(array $nums, int $k): array |
||
| 32 | { |
||
| 33 | if (empty($nums) || $k < 0) { |
||
| 34 | return []; |
||
| 35 | } |
||
| 36 | $n = count($nums); |
||
| 37 | for ($i = $n - 1; $i >= 0; $i--) { |
||
| 38 | $ans[] = ($nums[$i] + $k) % 10; |
||
| 39 | $k = (int) (($nums[$i] + $k) / 10); |
||
| 40 | } |
||
| 41 | while ($k > 0) { |
||
| 42 | $ans[] = $k % 10; |
||
| 43 | $k = (int) ($k / 10); |
||
| 44 | } |
||
| 45 | |||
| 46 | return array_reverse($ans); |
||
|
0 ignored issues
–
show
Comprehensibility
Best Practice
introduced
by
Loading history...
|
|||
| 47 | } |
||
| 48 | |||
| 49 | public static function addToArrayForm3(array $nums, int $k): array |
||
| 50 | { |
||
| 51 | if (empty($nums) || $k < 0) { |
||
| 52 | return []; |
||
| 53 | } |
||
| 54 | $n = count($nums); |
||
| 55 | for ($i = $n - 1; $i >= 0 || $k > 0; $i--) { |
||
| 56 | $ans[] = ($i >= 0 ? $nums[$i] + $k : $k) % 10; |
||
| 57 | $k = (int) (($i >= 0 ? $nums[$i] + $k : $k) / 10); |
||
| 58 | } |
||
| 59 | |||
| 60 | return array_reverse($ans); |
||
|
0 ignored issues
–
show
Comprehensibility
Best Practice
introduced
by
|
|||
| 61 | } |
||
| 62 | } |
||
| 63 |