LeetCode 9. 回文数 JAVA解法

原题目地址,想看原题目描述的可以点击查看:

https://leetcode-cn.com/problems/palindrome-number/

话不多说,直接上代码
思路:通过%10与/10得到各个位置数的倒置,将倒置的数计算后,和原数一致则表示是回文数。

/**
 * 判断一个数,是否是回文数
 *
 * @param x 待判断的数
 * @return 判断的结果,true:是回文数,false:不是回文数
 */
public boolean isPalindrome(int x) {
    int temp = x;
    int reverse = 0;
    if (x < 0) {
        return false;
    } else {
        while (x / 10 != 0) {
            reverse = reverse * 10 + x % 10;
            x /= 10;
        }
        reverse = reverse * 10 + x;
    }
    return temp == reverse;
}

上一种解法中是把数计算了,当然,也可以把各个位置的数存入集合容器,然后判断集合元素是否是对称的。

 /**
  * 判断一个数,是否是回文数
  *
  * @param x 待判断的数
  * @return 判断的结果,true:是回文数,false:不是回文数
  */
 public boolean isPalindrome(int x) {
     boolean result = true;
     List<Integer> lists = new ArrayList<>();
     if (x < 0) {
         result = false;
     } else {
         while (x / 10 != 0) {
             lists.add(x % 10);
             x /= 10;
         }
         lists.add(x);
     }
     for (int i = 0; i < lists.size() / 2; i++) {
         if (lists.get(i) != lists.get(lists.size() - i - 1)) {
             result = false;
             break;
         }
     }
     return result;
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值