LeetCode9. 回文数(Java)

题目:

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

示例:
LeetCode9. 回文数(Java)_第1张图片
代码:

  • 解法一
class Solution {
 public boolean isPalindrome(int x) {
 //将数字转化为字符串进行操作
		String s=String.valueOf(x);
		//利用夹逼思想对字符串的每个元素进行判断
		int head=0;
		int rear=s.length()-1;
		boolean flag=true;
		//只要头标记小于尾标记 循环继续
		while(head

代码解释:
LeetCode9. 回文数(Java)_第2张图片

  • 解法二
class Solution {
public boolean isPalindrome(int x) {
//数字小于0 一定不是回文数
		if (x < 0) {
			return false;
		}
		//将数字每一位拆分出来 倒序组装后 和原数字进行比较是否相等
		int oriNum = x;
		String s = "";
		//拆分出数字的每一位
		while (true) {
			if (x / 10 == 0) {
				s += x % 10;
				break;
			}
			s += x % 10;
			x/=10;
		}
		int newNum;
		//整数处于最大时2147483647 这里会抛出NumberFormatException异常 所以这里要解决异常
		try {
			
			newNum=Integer.parseInt(s);
		}catch(NumberFormatException e) {
			return false;
		}
		//判断原数字和新组成的数字是否相等
		if(oriNum==newNum) {
			return true;
		}
		return false;
	}
}
  • 别人的代码
class Solution {
    public boolean isPalindrome(int x) {
          if(x<0){
		    	return false;
		    }
		    int m=x;
		    int y=0;
		    while(x>0){
		    	y=y*10+x%10;
		    	x=x/10;
		    }
		    if(m==y){
		    	return true;
		    }else{
		    	return false;
		    }
    }
}

你可能感兴趣的:(LeetCode刷题)