LeetCode-9 Palindrome Number(判断是否为回文int型)

本文介绍了两种方法来判断整数是否为回文数,不使用额外的空间。第一种方法直接将整数转换为字符串并倒置比较;第二种方法通过位操作来计算每个位数,并进行比较。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode-9 Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

 

方法一:直接转String倒置

public class Solution {
    public boolean isPalindrome(int x) {
    	if (x < 0) {
    		return false;
	}
    	String xstr = String.valueOf(x);
    	for (int i = 0; i < xstr.length()/2; i++) {
    		if (xstr.charAt(i) == xstr.charAt(xstr.length()-1-i)) {
				continue;
			}else {
				return false;
			}
		}
    	return true;
    }
}

 

Runtime: 446 ms

 

方法二:

public class Solution {
	public boolean isPalindrome(int x) {
		if (x < 0) {
			return false;
		}
		int n = x;
		int x1 = x, x2 = x;
		int i = 0;//位数
		int pera = 0;
		int next = 0;
		for (i = 0; n > 0; i++) {
			n /= 10;
		}
		for (int j = i; j > i / 2; j--) {
			pera = (int) (x1 / Math.pow(10, j - 1));
			next = x2 % 10;
			if (pera == next) {
				x1 = (int) (x1 % Math.pow(10, j - 1));
				x2 = x2 / 10;
			} else {
				return false;
			}
		}
		return true;
	}
}


Runtime: 421 ms

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值