LeetCode之“数学”:Reverse Integer && Reverse Bits
2015-06-16 22:42
531 查看
1. Reverse Integer
题目链接题目要求:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
这道题主要要注意末尾为0和越界的问题。程序如下:
class Solution { public: int reverse(int x) { if(x == INT_MIN) return 0; int num = abs(x); int last = 0; long result = 0; while(num != 0) { last = num % 10; result = result * 10 + last; num /= 10; } if(result > INT_MAX) return 0; return (x > 0) ? result : -result; } };
2. Reverse Bits
题目链接题目要求:
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
Related problem: Reverse Integer
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
下边的程序中用到了bitset数据结构,需要注意的是,bits[0]才是最低位。
class Solution { public: uint32_t reverseBits(uint32_t n) { uint32_t one = 1; bitset<32> bits; int i = 31; while(n != 0 && i > -1) { bits[i] = n & one; n = n >> 1; i--; } return bits.to_ulong(); } };
相关文章推荐
- Redhat/CentOS系统KVM虚拟机安装过程详解
- android源码之工厂设计模式
- LeetCode---(119)Pascal's Triangle II
- 深入详解Oracle data change notification
- 夸平台telnet
- 如何通过反射调用类中的<泛型>方法
- 最近
- Mac配置Python开发环境并实现简单的字符串和整数拼接
- 20150616(杂记)
- 翻转链表
- Android 开发中使用Intent传递数据的方法
- 学 shell (1/5)
- Unity + iBatis + Asp.net Mvc 系统搭建
- C语言-判断闰年
- 智能指针
- 无限滑动的ViewPager
- Python读写文件
- JAVA语法细节(1)
- Java加载.class文件的几种方式
- 把VSO作为GitHub上JavaScript项目的免费CI服务器