美文网首页
9-Palindrome Number

9-Palindrome Number

作者: crishawy | 来源:发表于2019-02-18 21:35 被阅读0次

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

Example 1:

Input: 121
Output: true
Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:

Coud you solve it without converting the integer to a string?

my code

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<cmath>
#include<string>
#include<string.h>
#include<set>
#include<map>
#include<queue>
#include<stack>
using namespace std;

int main()
{
    int x;
    cin>>x;
    if(x<0)
    {
        cout<<false;
        return 0;
    }
    if(x==0)
    {
        cout<<true;
        return 0;
    }
    int i,j;
        int length = (int)log10(x);
        i = 0;
        j = length;
        int a1,a2;
        while(i<j)
        {
            a1 = (x/(int)round(pow(10,length-i)))%10;
            a2 = (x/(int)round(pow(10,length -j))) %10;
            if(a1 == a2)
            {
                i++;
                j--;
            }
            else break;
        }
        if(i >= j)
            cout<<true;
        else
            cout<<false;
}

refer code



    //整数进行半逆置
    int revertNumber = 0;
    while(x>revertNumber)
    {
        //常用的整数逆置操作
        revertNumber = revertNumber * 10 + x % 10;
        x /= 10;
    }
    if(x == revertNumber || x == revertNumber / 10)
        cout<<"true";
    else
        cout<<"false";
    return 0;
}

总结

1.该题的思想是进行整数的半逆置来判断是否是回文整数,常用的整数逆置方法是不断将尾数加上低位权值,即
revertNum = revertNum * 10 + x%10
2.该题本人使用的是数组思想,定义两个游标,一个右移,一个左移,只要其指向的数值不等,则返回false,直到两个游标相遇,返回true

相关文章

网友评论

      本文标题:9-Palindrome Number

      本文链接:https://www.haomeiwen.com/subject/nkazeqtx.html