Search code examples
c++bit-manipulationpalindrome

How do I input a binary number


I was doing a question on checking if a binary number is palindrome or not. The implementation I had could check it for 4 or 5 but as soon as I entered 1001 it interpreted it as thousand and one and not 9. How to do this?

 unsigned int rev=0;
 unsigned int temp=x;

 while(temp!=0)
 {
     cout<<rev<<" ";
     rev=(rev<<1)|(temp%2);
     temp=temp>>1;
     cout<<endl<<temp;

 }
 cout<<rev<<" ";
 if(rev==x)
     return true;
 else
     return false;

Solution

  • You can use strtol or any other function

    #include <iostream>
    
    int main(int argc, _TCHAR* argv[])
    {
        long x; 
        std::string str;
        std::cin >> str;
        char * pEnd;
        x = strtol(str.c_str(), &pEnd, 2);
        std::cout << x << std::endl;
        return 0;
    }