g2301_2400.s2396_strictly_palindromic_number.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g2301_2400.s2396_strictly_palindromic_number;
// #Medium #Math #Two_Pointers #Brainteaser #2022_09_14_Time_0_ms_(100.00%)_Space_40.6_MB_(75.27%)
/**
* 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:**
*
* * 4 <= n <= 105
**/
public class Solution {
public boolean isStrictlyPalindromic(int n) {
for (int i = 2; i <= n - 2; i++) {
String num = Integer.toString(i);
String s = baseConversion(num, 10, i);
if (!checkPalindrome(s)) {
return false;
}
}
return true;
}
private String baseConversion(String number, int sBase, int dBase) {
// Parse the number with source radix
// and return in specified radix(base)
return Integer.toString(Integer.parseInt(number, sBase), dBase);
}
private boolean checkPalindrome(String s) {
int start = 0;
int end = s.length() - 1;
while (start <= end) {
if (s.charAt(start) != s.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy