java - 在不转换为字符串的情况下检查 int 是否为回文?
问题描述
public class Palindrome {
public static void main(String args[]) {
int x = 121;
int res = 0;
while (x > 0) {
res = res * 10 + (x % 10);
x /= 10;
}
if (x - res == 0) {
System.out.println("True" + res);
} else
System.out.println("False" + res);
}
}
你好!此代码用于检查整数是否为回文而不将 转换int
为String
. 由于某种原因,计算机认为两者都代表数字res
并不相同。感谢您的帮助,并提前感谢!x
121
解决方案
你很亲密。这是一个基于您所做的解决方案:
static bool isPalindrome (int n1, int n2) {
return getReverseInteger(n1) == n2;
}
static int getReverseInteger (int n) {
int nReversed = 0;
while (n > 0) {
int digit = n % 10;
nReversed = nReversed * 10 + digit;
n = (n - digit) / 10;
}
return nReversed;
}
推荐阅读
- java - 在使用 restful API 向搜索引擎发送查询时使用高级搜索运算符
- node.js - 错误:Node Sass 尚不支持您当前的环境:Linux 64-bit with Unsupported runtime (72)
- python - 从 github 中的特定分支获取提交
- css - 横向多维列表
- scala - 在scala数据框中将日期格式从MM/dd/yyyy转换为yyyyMMdd
- flutter - 颤振图标未在 Iconbutton 中居中且对齐无任何作用
- aws-dms - 如何使用 AWS-DMS 将数据从我的 mongodb 数据库从 mlab 迁移到 dynamoDb
- typescript - Angular 7 - 从 Windows 应用程序复制图像并粘贴到 Web 应用程序不会保留图像的透明度
- c++ - 在 C++ 中,当一个数组的元素在循环中多次使用时,将它分配给另一个元素会更好吗?
- c# - 编译时如何在c#代码中以编程方式更改图标(主窗体+另一个子窗体)