File tree Expand file tree Collapse file tree 1 file changed +21
-0
lines changed Expand file tree Collapse file tree 1 file changed +21
-0
lines changed Original file line number Diff line number Diff line change @@ -5,6 +5,27 @@ List is periodically updated
5
5
## LeetCode
6
6
7
7
### #7 Reverse Integer
8
+
9
+ Using Math formulas to achieve the result
10
+
11
+ ```
12
+ var reverse = function(x) {
13
+ let result = 0;
14
+ // until x is zero
15
+ while (x != 0){
16
+ // add last digit of x derived as(x % 10) to the end of result as (num * 10) + anyNum
17
+ result = (result * 10) + (x % 10)
18
+
19
+ // remove the last digit of x from x using formula below
20
+ x = (x - (x % 10))/10
21
+ }
22
+
23
+ // check if within the range [-2^31, 2^31 -1] before returning result
24
+ if (result <= -Math.pow(2, 31) || result >= Math.pow(2, 31) - 1) return 0
25
+ return result
26
+ };
27
+ ```
28
+ By converting to string, less optimal
8
29
```
9
30
var reverse = function(x) {
10
31
// get the absolute value(non negative) and convert to String
You can’t perform that action at this time.
0 commit comments