LeetCode 9.回文数

  • 题目描述

给你一个整数 x ,如果 x是一个回文整数,返回 true ;否则,返回 false
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

  • 例如, 121 是回文,而 123 不是。
示例 1:
输入:x = 121
输出:true
示例 2:
输入:x = -121
输出:false
解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
  • 思路一:整数翻转(参考第七题)
    • 时间复杂度:O(n),n取决于x的位数
class Solution {
public:
	bool isPalindrome(int x) {
		// 边界判定
		if (x < 0 || x % 10 == 0 && x != 0) return false;
		if (x >= 0 && x < 10) return true;
		 
		int x0 = x;
		int y = 0;
		int n;

		while (x != 0) {
			n = x % 10;
			if (y > INT_MAX / 10) return false;
			y = y * 10 + n;
			x /= 10;
		}
		return true ? (x0 == y) : false;
	}
}
  • 思路二:转换成字符串(可以但没必要,有点慢)
  • 时间复杂度:O(n)
class Solution {
public:
	bool isPalindrome(int x) {
		if (x < 0 || x % 10 == 0 && x != 0) return false;
        if (x >= 0 && x < 10) return true;
        
        int x0 = x;
        
		char s[32];  // 顶多32位,再多就越界了
		int i = 0; // 可以用动态数组vector,但是会慢很多
		
		// convert to string
		while (x != 0) {
			s[i] = x % 10 + '0';
			x /= 10;
			i++;
		}
		
		int pre = 0, end = i - 1;
		while (pre <= end) {
            if (s[pre] != s[end]) return false;
            else {
                pre++;
                end--;
            }
        }
        return true;
	}
}
  • 思路三:整数翻转优化,只翻一半
  • 时间复杂度:O(logn)

  • 我们如何知道反转数字的位数已经达到原始数字位数的一半?

由于整个过程我们不断将原始数字除以 10,然后给反转后的数字乘上 10,所以,当原始数字小于或等于反转后的数字时,就意味着我们已经处理了一半位数的数字了。

class Solution {
public:
	bool isPalindrome(int x) {
		if (x < 0 || x % 10 == 0 && x != 0) return false;
		if (x >= 0 && x < 10) return true;
		//
		int revertedNumber = 0;
		while (x > revertedNumber) {
			revertedNumber = x % 10 + reverted * 10;
			x /= 10;
		}
		return x == revertedNumber || x == revertedNumber / 10;
	}
}
LeetCode 9.回文数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值