leetcode9. Palindrome Number

来源:互联网 发布:csgo 淘宝版 编辑:程序博客网 时间:2024/05/20 12:48

9. Palindrome Number

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

解法一

借助leetcode7方法,将整数逆转,判断是否相等,同时负数和整数溢出时均返回false。

public class Solution {    public boolean isPalindrome(int x) {        if(x < 0) {            return false;        }        int n = x;        int temp = 0;        int result = 0;        while (n != 0) {            temp = result * 10 + n % 10;            if(temp / 10 != result) {                return false;            }            n = n / 10;            result = temp;        }        if(result == x) {            return true;        } else {            return false;        }    }}

这里写图片描述

解法二

依次比较左一右一,左二右二……

public class Solution {    public boolean isPalindrome(int x) {         if (x < 0)            return false;        // initialize how many zeros        int div = 1;        while (x / div >= 10) {            div *= 10;        }        while (x != 0) {            int left = x / div;            int right = x % 10;            if (left != right)                return false;            x = (x % div) / 10;            div /= 100;        }        return true;    }}

这里写图片描述

0 0
原创粉丝点击