9-palindrome-number

题目描述:

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?

解答代码:

package com.jack.algorithm;

/**
 * create by jack 2018/10/23
 *
 * @auther jack
 * @date: 2018/10/23 23:48
 * @Description:
 * 判断一个整数是否是回文数
 */
public class PalindromeNumber {

    /**
     * 题目描述:
     *
     * https://leetcode.com/problems/palindrome-number/
     * @param x
     * @return
     */
    public static boolean isPalindrome(int x) {
        //如果是负数直接返回,肯定不是回文数
        if (x < 0) {
            return false;
        }
        int sum =0;
        int y = x;
        while (y!=0) {
            sum = sum *10 +y%10;
            y=y/10;
        }
        //重新组装的数和原先的相等,则返回true,否则返回false
        if (sum == x) {
            return true;
        }
        return false;
    }


    public static void main(String[] args) {
        boolean flag = isPalindrome(0);
        System.out.println("flag="+flag);
    }
}

源码地址:

扫描二维码关注公众号,回复: 3763046 查看本文章

源码

猜你喜欢

转载自blog.csdn.net/wj903829182/article/details/83349976
今日推荐