LeetCode Top100:回文串 & 整数反转

LeetCode Top100:回文串 & 整数反转_第1张图片

 

解法一:int转string然后双指针

注:

一、String转int有两种方式

(1)Integer.parseInt(str)

二、int转String有三种方式

(1)num + “”

(2)String.valueOf(num)

(3)Integer.toString(num)

(2)Integer.valueOf(str).intValue()

class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0) return false;
        if(x < 10) return true;

        char[] arr = Integer.toString(x).toCharArray();
        int n = arr.length;
        int i = 0, j = n - 1;
        while (i < j){
            if(arr[i] != arr[j]) return false;
            i++;
            j--;
        }
    return true;
    }
}

解法二:不用转换的做法,可以防止溢出

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

 

LeetCode Top100:回文串 & 整数反转_第2张图片

就是用的回文串的法二,避免了末尾为0的情况

这里注意: long可转int,int不能转long 原理https://blog.csdhgr/article/details/79604250dn.net/g

class Solution {
    public int reverse(int x) {
        int flag = x < 0 ? -1 : 1;
        x = flag * x;
        //int y = x;
        long res = 0;
        while(x > 0){
            res = res * 10 + x % 10;
            if(res > Integer.MAX_VALUE) return 0;
            x = x / 10;
        }
        return (int)res * flag;
    }
}

 

你可能感兴趣的:(leetCode)