LeetCode 9回文数

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

示例 1:

输入: 121
输出: true

示例 2:

输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0||x%10==0&&x!=0)
            return false;
        int ori=x;//将x保存至origin之中,为了与反转后的书进行比较
        int res=0;
        while(x!=0)
        {
            res=res*10+x%10;
            x/=10;
        }
        if(ori==res)
            return true;
        else
            return false;
    }
};

当然还有更好的方法就是将数字转化为字符串来进行比较,下面是一个范例,大家学习一下:

static auto static_lambda = []()
{
	std::ios::sync_with_stdio(false);
	std::cin.tie(0);
	return 0;
}();

class Solution {

public:
    bool isPalindrome(int x) {
        if(x<0)
            return false;
        if(x == 0)
            return true;
        char str[10];
        int i = -1;
        while(x!=0)
        {
            str[++i] =x%10+'0';
            x /= 10; 
            // putchar(str[i]);
        }
        for(int j =0;j<=i/2;++j)
        {
            // printf("%c %c\n",str[j],str[i-j]);
            if(str[j] != str[i-j])
                return false;
        }
       
        return true;
    }
};


猜你喜欢

转载自blog.csdn.net/qq_42020563/article/details/80342932
今日推荐