Menu Close

Leetcode 2396: Strictly Palindromic Number Solution

Here, we will help to understand about how to solve Strictly Palindromic Number Solution of leet code 2396 with code and algorithm.

You are given an integer n. An integer n is strictly palindromic if, for every base b between 2 and n - 2 (inclusive). The string representation of the integer n in base b is palindromic.

You are given an integer n, return true if n is strictly palindromic else false .

A string is palindromic if it reads the same forward and backward.

Example:

1)
Input: n = 9
Output: false
Explanation: In base 2: 9 = 1001 (base 2), which is palindromic.
In base 3: 9 = 100 (base 3), which is not palindromic.
Therefore, 9 is not strictly palindromic so we return false.
Note that in bases 4, 5, 6, and 7, n = 9 is also not palindromic.

2)
Input: n = 4
Output: false
Explanation: We only consider base 2: 4 = 100 (base 2), which is not palindromic.
Therefore, we return false.

Strictly Palindromic Number in C++

Code 1:

#include <iostream>
#include <set>
#include <vector>

using namespace std;

string convert_number_to_base(int n, int base) {
        string str = "";
        
        while(n) {
            str += to_string(n % base);
            n /= base;
        }
        return str;
    }
    
    bool check_palindrom(string str) {
        int str_len = str.length();
        
        for(int i = 0; i < str_len / 2; i++) {
            if(str[i] != str[str_len - i - 1]) {
                return false;
            }
        }
        return true;
    }
    
    bool isStrictlyPalindromic(int n) {
        for(int i = 2; i <= n - 2; i++) {
            string base_str = convert_number_to_base(n, i);
            bool is_palindrom = check_palindrom(base_str);
            
            if (!is_palindrom) {
                return false;
            }
        }
        return true;
    }
    
int main()
{
    cout<<isStrictlyPalindromic(7);

    return 0;
}

Output:

false

To check more leetcode problem’s solution. Pls click given below link:

https://www.techieindoor.com/category/leetcode/

Posted in C++, Leetcode, Medium

Leave a Reply

Your email address will not be published. Required fields are marked *