LeetCode之“数学”:Reverse Integer && Reverse Bits

  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和越界的问题。程序如下:

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4         if(x == INT_MIN)
 5             return 0;
 6             
 7         int num = abs(x);
 8         int last = 0;
 9         long result = 0; 
10         while(num != 0)
11         {
12             last = num % 10;
13             result = result * 10 + last;
14             num /= 10;
15         }
16         
17         if(result > INT_MAX)
18             return 0;
19         
20         return (x > 0) ? result : -result;
21     }
22 };

  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]才是最低位

 1 class Solution {
 2 public:
 3     uint32_t reverseBits(uint32_t n) {
 4         uint32_t one = 1;
 5         bitset<32> bits;
 6         int i = 31;
 7         while(n != 0 && i > -1)
 8         {
 9             bits[i] = n & one;
10             n = n >> 1;
11             i--;
12         }
13         
14         return bits.to_ulong();
15     }
16 };
原文地址:https://www.cnblogs.com/xiehongfeng100/p/4582024.html