9. Palindrome Number回文数(Easy,LeetCode)

Given an integer x, return true if x is palindrome integer.

给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。

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

  • For example, 121 is a palindrome while 123 is not.

回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。

Example 1:

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

Example 2:

Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

Example 3:

Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
解释:从右向左读, 为 01 。因此它不是一个回文数。

Constraints:提示:

  • -2^{31} <= x <= 2^{31} - 1

Follow up: Could you solve it without converting the integer to a string?

进阶:你能不将整数转为字符串来解决这个问题吗?

C语言:

bool isPalindrome(int x){
    long n=x,r=0;
    if(x<0) return false;
    if(x==0)    return true;
    while(n>0)
    {
        r=r*10+n%10;
        n=n/10;
    }
    return r==x;
}

执行结果:通过

执行用时:12 ms, 在所有 C 提交中击败了43.77%的用户

内存消耗:5.7 MB, 在所有 C 提交中击败了75.78%的用户

通过测试用例:11510 / 11510

不明白为什么int运行失败,只能把int改为long。

C语言:

bool isPalindrome(int x){
    long n=x,r=0;
    if(x<0) return false;
    if(x==0)    return true;
    while(n>0)
    {
        r=r*10+n%10;
        n=n/10;
    }
    if(r==x)
        return true;
    else
        return false;
}

执行结果:通过

执行用时:16 ms, 在所有 C 提交中击败了20.22%的用户

内存消耗:5.8 MB, 在所有 C 提交中击败了41.38%的用户

通过测试用例:11510 / 11510

C语言:

bool isPalindrome(int x){
    int i=0,j=0;
    char s[11]={'\0'};
    if(x<0) return false;
    if(x==0)    return true;
    while(x>0)
    {
        s[i]=x%10+'0';
        x=x/10;
        i++;
    }
    i--;
    while(j<i)
    {
        if(s[i]!=s[j])  return false;
        i--;
        j++;
    }
    return true;
}

执行结果:通过

执行用时:8 ms, 在所有 C 提交中击败了73.44%的用户

内存消耗:5.7 MB, 在所有 C 提交中击败了71.46%的用户

通过测试用例:11510 / 11510

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值