LeetCode 9. Palindrome Number

xiaoxiao2021-02-28  96

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

判断一个整数是不是回文结构。

首先想到的办法是利用反转整数,判断翻转后和原始整数是否相等。

public class Solution { public boolean isPalindrome(int x) { if(x<0){ return false; } long a = reverse(x); if(a==x){ return true; } return false; } public long reverse(int x){ long a = 0; while(x!=0){ a = a*10 + x; x = x/10; } return a; } }程序可以通过,不过发现排名很低,看了下前面的代码,发现了差距所在:

public class Solution { public boolean isPalindrome(int x) { if(x<0){ return false; } if(x<10){ return true; } if(x==0){ return false; } int a = 0; while(x!=0){ a = a*10 + x; x = x/10; if(a!=0&&(a==x||a==x/10)){ return true; } } return false; } }可以先判断是否为负、是否是个位数、个位是否为0来进行筛选,剩下的只需要进行一半的循环判断,即x的位数还剩一半时,逆序数和原始数是应该相等的,这样可以节省很多时间。

转载请注明原文地址: https://www.6miu.com/read-45500.html

最新回复(0)