-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplus-one.php
64 lines (52 loc) · 1.29 KB
/
plus-one.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<!DOCTYPE html>
<html>
<body>
<?php
/*
Problem: https://leetcode.com/problems/plus-one/description/
Lesson learned:
- another problem dealing with limitation of float
- copying entire array takes up time & memory -> avoid if you can
*/
$digits = array(9);
$solution = new Solution();
$result = $solution->plusOne($digits);
var_dump($result);
class Solution {
/**
* @param Integer[] $digits
* @return Integer[]
*/
//solution - runtime 0ms beats 100%, memory 10.84MB beats 79.23%
function plusOne($digits) {
$d = array();
$index = count($digits)-1;
$increment = true;
for($x = $index; $x > -1; $x--){
$n = $digits[$x];
if($increment){
$n++;
}
if($n > 9){
array_unshift($d, 0);
$increment = true;
if($x == 0){
array_unshift($d, 1);
break;
}
}else{
$increment = false;
array_unshift($d, $n);
}
}
return $d;
}
//works with int but not with float
function plusOneLimited($digits) {
$num = intval(implode($digits));
return str_split(strval($num+1));
}
}
?>
</body>
</html>