C++ program to find all numbers less than n, which are palindromic in base 10 and base 2.
Find all numbers less than n, which are palindromic in base 10 as well as base 2. Examples:
33 is Palindrome in its decimal representation. 100001(binary equivalent of 33) in Binary is a Palindrome. 313 is Palindrome in its decimal representation. 100111001 (binary equivalent of 313) in Binary is a Palindrome.
Brute Force: We check all the numbers from 1 to n whether their decimal representation is palindrome or not. Further, if a number is palindromic in base 10 then we check for its binary representation. If we found both representations a palindrome then we print it. Efficient Approach: We start from 1 and create palindromes of odd digit and even digit up to n and check whether its binary representation is palindrome or not. Note: This will reduce the number of operations as we should check only for decimal palindrome instead of checking all numbers from 1 to n. This approach uses two methods: int createPalindrome(int input, int b, bool isOdd): The palindrome creator takes in an input number and a base b as well as a boolean telling if the palindrome should have an even or odd number of digits. It takes the input number, reverses it, and appends it to the input number. If the result should have an odd number of digits, it chops off a digit of the reversed part. bool IsPalindrome(int number, int b) It takes the input number and calculates its reverse according to base b. Return result whether the number is equal to its reverse or not.
1 3 5 7 9 313 585 717 33 99
Time Complexity: O(N*log(N)), as we are using the while loop to loop over N times in the worst case and IsPalindrome cost O(log(N)) which is nested inside the while loop.
Auxiliary Space: O(1), as we are not using any extra space.
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.