Skip to content

Commit 74efb75

Browse files
authored
Merge pull request #1066 from srinivas892/main
Create Reverse_Integer.cpp
2 parents 428b69d + dcbfe1f commit 74efb75

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Math/Reverse_Integer.cpp

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/* 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.
2+
3+
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
4+
Example 1:
5+
6+
Input: x = 123
7+
Output: 321
8+
Example 2:
9+
10+
Input: x = -123
11+
Output: -321
12+
Example 3:
13+
14+
Input: x = 120
15+
Output: 21
16+
17+
18+
Constraints:
19+
20+
-2^31 <= x <= 2^31 - 1
21+
*/
22+
// function for reversing the integer;
23+
24+
int reverse(int x) {
25+
int ans =0;
26+
if(x > INT_MAX || x < INT_MIN) // checking the integer is in range of -2^31 <= x <= 2^31 - 1
27+
return 0;
28+
while(x != 0){
29+
if(ans > INT_MAX/10 || ans < INT_MIN/10) // -2^31 <= x <= 2^31 - 1 this condition for border values of range
30+
return 0;
31+
ans = ans*10; // we increaing the unit position each itereation
32+
ans += x%10; // here we finding the last unit elemet so that we can add in ans
33+
x /=10; // decreamenting the value or we can say elemenating the last unit element that we are find
34+
35+
}
36+
return ans; // returning the ans;
37+
}

0 commit comments

Comments
 (0)