9. Palindrome Number 【Easy】

avatar 2020年08月30日22:35:49 6 1821 views
博主分享免费Java教学视频,B站账号:Java刘哥

Question

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true

Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?

 

My Answer

实现方式有点 low,直接反过来,然后比较两个数字是否相对。还可以优化

class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0) {
            return false;
        }
        int v = x, y = 0;
        while(x > 0) {
            y = y * 10 +  x % 10;
            x = x /10;
        }
        return v == y;
    }
}

 

  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0