您的位置:首页 > 编程语言

Leetcode 编程训练笔记-Reverse Integer

2015-01-05 21:55 411 查看
7.Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

意思是很简单,但特别需要注意判断转换后的数字是越界的情况,要在乘10前判断是否会越界,具体如下

if ( (ret > (INT_MAX/10)) || (ret < (INT_MIN/10))){

return 0;

}

ret = ret*10 + x%10;

之前犯了个错误就是在乘10后判断是否越界,用跟x符号相异来判断,但有可能在乘10后的真实值是越界的,却在4字节整型中表现为符号相同的一个未知的数字,与想要的答案完全不一样。

4字节有符号整型最大值为2147483647,最小值为-2147483648,但一定要注意如果像下面判断有会有问题

if(ret < -2147483648)

具体参考网址

http://stackoverflow.com/questions/14695118/2147483648-0-returns-true-in-c

-2147483648
 is
not a “number”. C++ language does not support negative literal values.

-2147483648
 is
actually an expression: a positive literal value 
2147483648
 with unary 
-
 operator
in front of it. Value 
2147483648
 is apparently too large for the positive side
of 
int
 range on your platform. If type 
long
int
 had greater range on your platform, the compiler would have to automatically assume that 
2147483648
 has 
long
int
 type. (In C++11 the compiler would also have to consider 
long long int
 type.)
This would make the compiler to evaluate 
-2147483648
 in the domain of larger
type and the result would be negative, as one would expect.

However, apparently in your case the range of 
long
int
 is the same as range of 
int
, and in general there’s no integer type
with greater range than 
int
 on your platform. This formally means that positive
constant 
2147483648
 overflows all available signed integer types, which in turn
means that the behavior of your program is undefined. (It is a bit strange that the language specification opts for undefined behavior in such cases, instead of requiring a diagnostic message, but that’s the way it is.)

In practice, taking into account that the behavior is undefined, 
2147483648
 might
get interpreted as some implementation-dependent negative value which happens to turn positive after having unary 
-
applied
to it. Alternatively, some implementations might decide to attempt using unsigned types to represent the value (for example, in C89/90 compilers were required to use 
unsigned
long int
, but not in C99 or C++). Implementations are allowed to do anything, since the behavior is undefined anyway.

As a side note, this is the reason why constants like 
INT_MIN
 are
typically defined as
#define INT_MIN (-2147483647 - 1)
[/code]

instead of the seemingly more straightforward
#define INT_MIN -2147483648
[/code]

The latter would not work as intended.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode