美文网首页
7. Reverse Integer

7. Reverse Integer

作者: BadGirl_TONG | 来源:发表于2018-01-31 10:40 被阅读0次

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input:123Output:321

Example 2:

Input:-123Output:-321

Example 3:

Input:120Output:21

Note:

Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

solution:

https://www.jianshu.com/p/27b0baa6f6bf

思路:

如果以最高位为符号位,二进制原码最大为0111111111111111=2的15次方减1=32767

最小为1111111111111111=-2的15次方减1=-32767

此时0有两种表示方法,即正0和负0:0000000000000000=1000000000000000=0

所以,二进制原码表示时,范围是-32767~-0和0~32767,因为有两个零的存在,所以不同的数值个数一共只有2的16次方减1个,比16位二进制能够提供的2的16次方个编码少1个。

还需要考虑反转后的数字是否越界,if 判断不全。

相关文章

网友评论

      本文标题:7. Reverse Integer

      本文链接:https://www.haomeiwen.com/subject/sddkzxtx.html