Search code examples
algorithmnumber-systems

how to find total number of numbers whose binary representation is palindrome?


What is the best approach to find the total number of numbers between two given numbers whose binary representation is palindrome? The problem I am trying to solve is here on spoj http://www.spoj.com/problems/BINPALI/


Solution

  • I solved the spoj problem and code as below:

    #include<iostream>
    #include<algorithm>
    #include<cctype>
    #include<cstring>
    #include<string>
    using namespace std;
    int main()
    {
      int a,b,t;
      cin>>t;
      while(t--)
      {
         cin>>a>>b;
         int total=0;
         string s="";
         while(a<=b)
         {
           s="";
           for(int i=a;i>0;i=i/2)
           {
             if(i%2)
                s+='1';
             else
                s+='0';
           }
          string s2="",s3="";
          s2=s.substr(0,s.length()/2);
          int k=s.length();
          if(k%2)
            s3=s.substr(s.length()/2+1,s.length());
          else
            s3=s.substr(s.length()/2,s.length());
          reverse(s2.begin(),s2.end());
          if(s2==s3)
          {
             cout<<a<<" ";
             total++;
          }
          a++;
       }
    if(!total)
        cout<<"none"<<endl;
    }
    return 0;
    }