https://leetcode.com/problems/reverse-bits/
Reverse bits of a given the unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 ( Represented in binary as00111001011110000010100101000000).
The simple thing is to walk through it, but this method is inefficient, and there seems to be no better way to do it.
Class Solution {public: uint32_t reversebits (uint32_t N) { if (0 = = N) { return 0; } int res = 0; for (int i = 0; i <; i++) { if (N & 1) { res + = (1 << (31-i)); } n = n >> 1; } return res; }};
Number of 1 Bits
https://leetcode.com/problems/number-of-1-bits/
Write a function that takes an unsigned integer and returns the number of ' 1 ' bits it has (also known as the Hamming weigh T).
For example, the 32-bit integer ' One ' 00000000000000000000000000001011
has a binary representation, so the function should return 3.
Note here that n& (n-1) can eliminate the last 1, so do not have to traverse it all over again, how many 1, how many times
Class Solution {public: int hammingweight (uint32_t n) { if (0 = = N) { return 0; } int res = 0; while (n) { n = n& (n-1); res++; } return res; }};
Reverse Integer
https://leetcode.com/problems/reverse-integer/
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return-321 Here the calculation process is not complicated, but notice whether the range is exceeded
Class Solution {public: int reverse (int x) { long long xx = x;//Prevent negative numbers from exceeding if (0 = = x) { return 0; } int flag = 0; if (x < 0) { flag = 1; xx =-X; } stack<int> temp; while (xx) { temp.push (xx%10); xx = XX/10; } Long long index = 1; Long long res = 0; while (!temp.empty ()) { res + = Temp.top () *index; index = index*10; Temp.pop (); } if (flag) { res = res* ( -1); if (res < int_min) return 0; } if (res > Int_max) { return 0; } return res; }};
Leetcode-reverse Bits, 1 bit and number binary case correlation