Java回文数统计1-999999
时间: 2024-06-15 16:04:14 浏览: 14
Java回文数统计1-999999的方法如下:
```java
public class PalindromeCount {
public static void main(String[] args) {
int count = 0;
for (int i = 1; i <= 999999; i++) {
if (isPalindrome(i)) {
count++;
}
}
System.out.println("1-999999之间的回文数个数为:" + count);
}
// 判断一个数是否是回文数
public static boolean isPalindrome(int num) {
int originalNum = num;
int reverseNum = 0;
while (num != 0) {
int digit = num % 10;
reverseNum = reverseNum * 10 + digit;
num /= 10;
}
return originalNum == reverseNum;
}
}
```
相关问题
字符串的回文子串 java
好的,以下是Java实现字符串的回文子串的代码示例:
```java
public class PalindromicSubstring {
public int countSubstrings(String s) {
int n = s.length();
int count = 0;
boolean[][] dp = new boolean[n][n];
// 枚举回文子串的长度
for (int len = 1; len <= n; len++) {
// 枚举回文子串的起始位置
for (int i = 0; i + len - 1 < n; i++) {
int j = i + len - 1;
if (len == 1) { // 单个字符是回文子串
dp[i][j] = true;
} else if (len == 2) { // 两个相同字符是回文子串
dp[i][j] = (s.charAt(i) == s.charAt(j));
} else { // 多个字符时,判断首尾字符是否相同,以及中间部分是否为回文子串
dp[i][j] = (s.charAt(i) == s.charAt(j)) && dp[i+1][j-1];
}
if (dp[i][j]) {
count++;
}
}
}
return count;
}
}
```
这里使用动态规划的思想,时间复杂度为 $O(n^2)$,空间复杂度也是 $O(n^2)$。具体做法是:定义 $dp[i][j]$ 表示字符串从 $i$ 到 $j$ 是否是回文子串,然后根据回文子串的定义进行状态转移。最后统计回文子串的数量即可。
字符串的回文子串 java 中心扩展
好的,以下是Java实现字符串的回文子串的中心扩展算法的代码示例:
```java
public class PalindromicSubstring {
public int countSubstrings(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
// 以i为中心,向左右扩展
int len1 = expandFromCenter(s, i, i);
// 以i和i+1为中心,向左右扩展
int len2 = expandFromCenter(s, i, i + 1);
count += len1 + len2;
}
return count;
}
private int expandFromCenter(String s, int left, int right) {
int count = 0;
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
count++;
left--;
right++;
}
return count;
}
}
```
这里的思路是:枚举每个可能的中心位置,然后以该中心位置向左右两侧扩展,直到不能扩展为止。具体实现时,需要分别处理回文子串长度为奇数和偶数的情况,最后统计回文子串的数量即可。时间复杂度为 $O(n^2)$,空间复杂度为 $O(1)$。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)