leetcode_3. palindrome

  • Palindrome: to determine whether an integer is a palindrome. Palindrome correct order (from left to right) and reverse (right to left) reading is the same integer.
示例 1:

输入: 121
输出: true

示例 2:

输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

示例 3:

输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。

进阶:你能不将整数转为字符串来解决这个问题吗?
  • To do this problem when I think the idea is very clear, first of all based on its three examples, you will know that you can exclude the first and the last one is a negative integer greater than 0 and 10 are not a palindrome. Further determines whether the number of palindromic may be split into integer array, the number of the array are equal compared for symmetry.
  • When execution: 4 ms, beat all C submission of 99.57% of user
    memory consumption: 7.1 MB, defeated 87.30% of all users in C submission
bool isPalindrome(int x){
    int tmp[32]={0};
    int m,n,i;
    //可以首先排除负数和最后一位为0且大于10的整数均不是回文数
    if((x<0)||(x>10&&x%10==0))
        return false;
    for (i = 0; x != 0; i++)  //这里的x!=0很重要
    {
        tmp[i] = x % 10;  //tmp存储了x的每一位
        x = x / 10;
    }
    for(m=0,n=i-1;m<=n;m++,n--)
    {
        if(tmp[m]!=tmp[n])
            return false;
    }
    return true;
}
Published 77 original articles · won praise 19 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_42932834/article/details/95194106