LeetCode:ReverseBits
Problem:
https://leetcode.com/problems/reverse-bits/My brute force solutions get accepted,the algorithm is to push all the remainders into a stack and then multiplying each bit with corresponding power of 2
#include<bits/stdc++.h> using namespace std; class Solution { public: int reverseBits(int n) { int x=1,i=0; long long res=0; stack<int>st; while(x<=32) { st.push(abs(n%2)); n>>=1; x++; } res=0; while(!st.empty()) { res+=(st.top()*(pow(2,i))); i++; st.pop(); } return res; } };
Reference :
HereMethod 2
#include<bits/stdc++.h> #define INT_SIZE 32 using namespace std; class Solution { public: int reverseBits(unsigned int num) { int i=INT_SIZE-1; unsigned int rev_num=0; while(i>=0 && num) { if(num & 1) rev_num |= (1<<i); num>>=1; i--; } return rev_num; } }; int main() { Solution s; cout<<s.reverseBits(8)<<endl; }
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment