Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 48af0c6

Browse files
author
ongch
committed
add: reverse integer
1 parent 675f694 commit 48af0c6

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
Reverse Integer
3+
https://leetcode.com/problems/reverse-integer/
4+
5+
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
6+
7+
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
8+
9+
Example 1:
10+
Input: x = 123
11+
Output: 321
12+
13+
Example 2:
14+
Input: x = -123
15+
Output: -321
16+
17+
Example 3:
18+
Input: x = 120
19+
Output: 21
20+
21+
*/
22+
23+
/**
24+
* @param {number} x
25+
* @return {number}
26+
*/
27+
var reverseInteger = function(x) {
28+
const sign = x >= 0 ? 1 : -1;
29+
30+
let baseNum = sign * x;
31+
let builder = 0;
32+
33+
while (baseNum > 0) {
34+
const digit = baseNum % 10;
35+
builder = builder * 10 + digit;
36+
baseNum = (baseNum / 10) | 0;
37+
}
38+
39+
builder *= sign;
40+
41+
const isWithinRange = (builder >= -Math.pow(2, 31) && builder <= Math.pow(2, 31) - 1);
42+
43+
return isWithinRange ? builder : 0;
44+
};
45+
46+
module.exports.reverseInteger = reverseInteger;

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ To run a specific problem in your console run `node <problem_file_path>` (e.g.
6262
| [Construct Binary Tree from Preorder and Inorder Traversal ](/LeetcodeProblems/Algorithms/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.js) | Medium | https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ |
6363
| [Lowest Common Ancestor of a Binary Tree ](/LeetcodeProblems/Algorithms/Lowest_Common_Ancestor_of_a_Binary_Tree.js) | Medium | https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ |
6464
| [Maximum Sum of an Hourglass](/LeetcodeProblems/Algorithms/Maximise_Hour_Glass_Sum.js) | Medium | https://leetcode.com/problems/maximum-sum-of-an-hourglass/ |
65+
| [Reverse Integer](/LeetcodeProblems/Algorithms/Reverse_Integer.js) | Medium | https://leetcode.com/problems/reverse-integer/ |
6566
| [Flood Fill ](/LeetcodeProblems/Algorithms/Flood_Fill.js) | Easy | https://leetcode.com/problems/flood-fill/ |
6667
| [Implement stack using queues ](/LeetcodeProblems/Algorithms/Implement_stack_using_queues.js) | Easy | https://leetcode.com/problems/implement-stack-using-queues/ |
6768
| [Number of Segments in a String ](/LeetcodeProblems/Algorithms/Number_of_Segments_in_a_String.js) | Easy | https://leetcode.com/problems/number-of-segments-in-a-string/ |

0 commit comments

Comments
 (0)