I need help with a code that check if a binary number is palindrome. Suppose that the input is 21 (10101). In the function i do that:
-copy the value of num1 to num2
-now num1 is 00010101 and num2 is 00010101
-shift(right) the bit of num1 while num1>0
-now num1 is: 00000000|10101000 and num2 is 00010101|00000000
-shift (left) only one position the bit of num1
-now num1 is: 00000001|01010000 and num2 is 00010101|00000000
-now while num1 != num2 i compare the bit and shift num1 left, and num2 right, each loop.
-compare example:
00000001|01010000
00010101|00000000
|
V
1==1
next loop the compare is 0==0
So my code is the following. And i have a problem, because i dont know how to stop the last while (while with while condition: num1!=num2 && flag==true). Obviousbly the condition that i write is not the right way. But i dont how to do that. In this specific case i want to stop it if it checks 5 digit. An then i want to ask if the solution that i do is too difficult, and if there is other way to solve the problem (ps: its normal that i find it difficult? Because i thought to solve it transform the decimal number in binary manually using the while (n>0) -> n%2, than memorize the bit in an array, and do an easy algorithm on the array to check the reverse; but now i want to redo the problem using << and >> operator). Thank you all.
#include <iostream>
using namespace std;
int palindrome(unsigned short);
int main()
{
unsigned short num;
cout << "Inserisci un numero:\t";
cin >> num;
if (palindrome(num) == 1)
cout << "Palindrome" << endl;
else
cout << "Not palindrome" << endl;
cout << "\a";
return 0;
}
int palindrome(unsigned short num1)
{
unsigned short num2 = num1;
bool flag = true;
while (num1>0)
{
num1 >>= 1;
}
num1 <<= 1;
while ((num1 != num2) && (flag == true))
{
if ((num1 & 1) != (num2 & 1))
{
flag = false;
break;
}
num1 <<= 1;
num2 >>= 1;
}
return flag;
}