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.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Solution
Because the limit of the problem, we can’t use long number to calculate the number.
With C#, the first idea is to use Int32.TryParse, which can easily check if bigger or smaller than Int32.
And let us try of that.
C# Solution
Solution1 (use string to reverse and Int32.TryParse to check the result)
public class Solution {
public int Reverse(int x) {
bool neg = false; //check if negative number
if(x<0)
{
neg = true;
x = x*-1;
}
//Convert to string than reverse by Array
string y = x.ToString();
char[] arr = y.ToCharArray();
Array.Reverse(arr);
y = new string(arr);
int res = 0;
if(Int32.TryParse(y,out res))
{
res *= neg ? -1 : 1;
}
return res;
}
}
❌Solution2 (the solution is too superfluous and complex)
public class Solution {
public int Reverse(int x) {
bool neg = false; //check if negative number
if(x<0)
{
neg = true;
x = x*-1;
}
string y = x.ToString();
char[] arr = y.ToCharArray();
Array.Reverse(arr);
y = new string(arr);
//calculate and check
int res = 0;
for(int i =0; i<y.Length;i++)
{
int tmp = (int)(Convert.ToInt32(y[i].ToString()) *Math.Pow(10,y.Length-i-1));
if(tmp == Int32.MinValue || tmp == Int32.MaxValue)
{
return 0;
}
if(neg)
{
tmp *= -1;
}
if(tmp > Int32.MaxValue-res && !neg)
{
return 0;
}
else if( Int32.MinValue-res >tmp &&neg)
{
return 0;
}
res += tmp;
}
return res;
}
}
⭐Solution 3
public class Solution {
public int Reverse(int x) {
int res = 0;
while(x !=0)
{
int tmp = x%10;
res = res*10+tmp;
x = (x-tmp)/10;
if(res%10!=tmp) //exceed int range
{
return 0;
}
}
return res;
}
}
【res%10!=tmp】 is to check if the res number exceed the Int32 range, than return 0
Java Solution
Solution1
class Solution {
public int reverse(int x) {
boolean neg = false; //check if negative number
if(x<0)
{
neg = true;
x = x*-1;
}
//Convert to string than reverse by Array
String y = Integer.toString(x);
StringBuilder sb=new StringBuilder(y);
y = sb.reverse().toString();
try {
x = Integer.parseInt(y);
} catch (NumberFormatException e) {
return 0;
}
if(neg)
{
x*=-1;
}
return x;
}
}
Use try catch to pretend C# ‘s Int32.TryParse function
Runtime : 3ms
Solution2
class Solution {
public int reverse(int x) {
int res = 0;
while(x !=0)
{
int tmp = x%10;
res = res*10+tmp;
x = (x-tmp)/10;
if(res%10!=tmp) //exceed int range
{
return 0;
}
}
return res;
}
}
⭐Runtime : 2ms
Python3 Solution
Solution1
class Solution:
def reverse(self, x: int) -> int:
x = str(x)
if x[0] == '-':
a = int('-' + x[-1:0:-1])
if a >= -2147483648 and a<= 2147483647:
return a
else:
return 0
else:
a = int(x[::-1])
if a >= -2147483648 and a<= 2147483647:
return a
else:
return 0
JavaScript Solution
Solution1
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
var res = 0;
while(x !=0)
{
var tmp = x%10;
res = res*10+tmp;
x = (x-tmp)/10;
if (res < -2147483648 || res > 2147483647)
{
return 0;
}
}
return res;
};
C++ Solution
class Solution {
public:
int reverse(int x) {
int res = 0;
while (x != 0) {
int tmp = x % 10;
if (res > INT_MAX / 10 || (res == INT_MAX / 10 && tmp > 7)) {
return 0;
}
if (res < INT_MIN / 10 || (res == INT_MIN / 10 && tmp < -8)) {
return 0;
}
res = res * 10 + tmp;
x = (x - tmp) / 10;
}
return res;
}
};
And why we need to check 7 and -8, that is because we need to check if the number will be overflow of integer range .
INT_MIN = -231 = -2,147,483,648
INT_MAX = 231-1 = 2,147,483,647
Conclusion
This is an interesting problem, like C#, you can use Library TryParse to get the answer easily.
But I thought the best way to finish this problem is the solution3.
"the reverse side also has a reverse side"
Japanese proverb
well in c++, this question is a bug and cant be solved. i used ur trick
if(res%10!=tmp) //exceed int range
{
return 0;
}
but i still dont get it.
if u dont get what im saying im on leet code question 7. How to reverse a string.
Plz provide a c++ solution also.
Thanks for your comment, I have updated the c++ solution with explanation.
If you still got any problem, I will reply asap.
var uagb_data = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","uagb_masonry_ajax_nonce":"618dc5a2c3"};
var uagb_data = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","uagb_masonry_ajax_nonce":"618dc5a2c3","uagb_grid_ajax_nonce":"e0999a8b4d"};
document.addEventListener("DOMContentLoaded", function(){
( function( $ ) {
var cols = parseInt( '3' );
var $scope = $( '.uagb-block-9f310610' );
let imagePosition = 'top';if( 'top' !== imagePosition ){
// This CSS is for Post BG Image Spacing
let articles = document.querySelectorAll( '.uagb-post__image-position-background .uagb-post__inner-wrap' );
if( articles.length ) {
for( let article of articles ) {
let image = article.getElementsByClassName('uagb-post__image');
if ( image[0] ) {
let articleWidth = article.offsetWidth;
let rowGap = 20;
let imageWidth = 100 - ( rowGap / articleWidth ) * 100;
image[0].style.width = imageWidth + '%';
image[0].style.marginLeft = rowGap / 2 + 'px';
}
}
}
}
// If this is not a Post Carousel, return.
// Else if it is a carousel but has less posts than the number of columns, return after setting visibility.
if ( ! $scope.hasClass('is-carousel') ) {
return;
} else if ( cols >= $scope.children('article.uagb-post__inner-wrap').length ) {
$scope.css( 'visibility', 'visible' );
return;
}
var slider_options = {
'slidesToShow' : cols,
'slidesToScroll' : 1,
'autoplaySpeed' : 2000,
'autoplay' : Boolean( '1' ),
'infinite' : Boolean( '1' ),
'pauseOnHover' : Boolean( '1' ),
'speed' : 500,
'arrows' : Boolean( '1' ),
'dots' : Boolean( '1' ),
'rtl' : Boolean( '' ),
'prevArrow' : '<button type=\"button\" data-role=\"none\" class=\"slick-prev\" aria-label=\"Previous\" tabindex=\"0\" role=\"button\"><svg width=\"20\" height=\"20\" viewBox=\"0 0 256 512\"><path d=\"M31.7 239l136-136c9.4-9.4 24.6-9.4 33.9 0l22.6 22.6c9.4 9.4 9.4 24.6 0 33.9L127.9 256l96.4 96.4c9.4 9.4 9.4 24.6 0 33.9L201.7 409c-9.4 9.4-24.6 9.4-33.9 0l-136-136c-9.5-9.4-9.5-24.6-.1-34z\"></path></svg><\/button>',
'nextArrow' : '<button type=\"button\" data-role=\"none\" class=\"slick-next\" aria-label=\"Next\" tabindex=\"0\" role=\"button\"><svg width=\"20\" height=\"20\" viewBox=\"0 0 256 512\"><path d=\"M224.3 273l-136 136c-9.4 9.4-24.6 9.4-33.9 0l-22.6-22.6c-9.4-9.4-9.4-24.6 0-33.9l96.4-96.4-96.4-96.4c-9.4-9.4-9.4-24.6 0-33.9L54.3 103c9.4-9.4 24.6-9.4 33.9 0l136 136c9.5 9.4 9.5 24.6.1 34z\"></path></svg><\/button>',
'responsive' : [
{
'breakpoint' : 1024,
'settings' : {
'slidesToShow' : 2,
'slidesToScroll' : 1,
}
},
{
'breakpoint' : 767,
'settings' : {
'slidesToShow' : 1,
'slidesToScroll' : 1,
}
}
]
};$scope.imagesLoaded( function() {
$scope.slick( slider_options );
}).always( function() {
$scope.css( 'visibility', 'visible' );
} );var enableEqualHeight = ( '1' );if( enableEqualHeight ){
$scope.imagesLoaded( function() {
UAGBPostCarousel?._setHeight( $scope );
});$scope.on( 'afterChange', function() {
UAGBPostCarousel?._setHeight( $scope );
} );
}} )( jQuery );
});
ai_front = {"insertion_before":"BEFORE","insertion_after":"AFTER","insertion_prepend":"PREPEND CONTENT","insertion_append":"APPEND CONTENT","insertion_replace_content":"REPLACE CONTENT","insertion_replace_element":"REPLACE ELEMENT","visible":"VISIBLE","hidden":"HIDDEN","fallback":"FALLBACK","automatically_placed":"Automatically placed by AdSense Auto ads code","cancel":"Cancel","use":"Use","add":"Add","parent":"Parent","cancel_element_selection":"Cancel element selection","select_parent_element":"Select parent element","css_selector":"CSS selector","use_current_selector":"Use current selector","element":"ELEMENT","path":"PATH","selector":"SELECTOR"};
well in c++, this question is a bug and cant be solved. i used ur trick
if(res%10!=tmp) //exceed int range
{
return 0;
}
but i still dont get it.
if u dont get what im saying im on leet code question 7. How to reverse a string.
Plz provide a c++ solution also.
Thanks for your comment, I have updated the c++ solution with explanation.
If you still got any problem, I will reply asap.