LeetCode in Kotlin

2396. Strictly Palindromic Number

Medium

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.

Given an integer n, return true if n is strictly palindromic and false otherwise.

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.

Example 2:

Input: n = 4

Output: false

Explanation: We only consider base 2: 4 = 100 (base 2), which is not palindromic.

Therefore, we return false.

Constraints:

Solution

class Solution {
    fun isStrictlyPalindromic(n: Int): Boolean {
        for (i in 2..n - 2) {
            val num = Integer.toString(i)
            val s = baseConversion(num, 10, i)
            if (!checkPalindrome(s)) {
                return false
            }
        }
        return true
    }

    private fun baseConversion(number: String, sBase: Int, dBase: Int): String {
        // Parse the number with source radix
        // and return in specified radix(base)
        return Integer.toString(number.toInt(sBase), dBase)
    }

    private fun checkPalindrome(s: String): Boolean {
        var start = 0
        var end = s.length - 1
        while (start <= end) {
            if (s[start] != s[end]) {
                return false
            }
            start++
            end--
        }
        return true
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy