9.Palindrome Number

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


Example 3:

Input: 10

Output: false

Follow up:

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


关键点:

1.负数均不是回文数

2.若为正数,则判断原数和翻转数是否相等。

3.函数返回值是bool变量,所以应该return true,而不是return “true”;


#include

#include<climits>

using namespace std;

stringinverse(intx){

    if(x<0)

        return"false";

    intnewnum=0,oldnum=x;

    while(oldnum!=0)

    {

        newnum=newnum*10+oldnum%10;

        oldnum=oldnum/10;

    }

    if(x==newnum)

        return"true";

    else

        return"false";

}

intmain(intargc,constchar* argv[]) {

    // insert code here...

    inta;

    while(cin>>a){


            cout<

    }

    cout << "Hello, World!\n";

    return 0;

}


网上其他的代码,其思路:每次提取头尾两个数,判断它们是否相等,判断后去掉头尾两个数


class Solution {

public:

    bool isPalindrome(int x) {


        //negative number

        if(x < 0)

            return false;


        int len = 1;

        while(x / len >= 10)

            len *= 10;


        while(x > 0)    {


            //get the head and tail number

            int left = x / len;

            int right = x % 10;


            if(left != right)

                return false;

            else    {

                //remove the head and tail number

                x = (x % len) / 10;

                len /= 100;

            }

        }


        return true;

    }

};

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • Android音频系统详解 参考好文: Android 音频系统:从 AudioTrack 到 AudioFlin...
    爱雨520阅读 13,797评论 2 7
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,918评论 0 38
  • 时间过的好快,一转眼在小白训练营的日子已经接近尾声,回过头去,14天前那个焦虑迷茫的自己恍如隔世。每个月都...
    230黑白灰阅读 261评论 0 5
  • 明天就是端午节啦。几个玩的好的同学准备在宿舍一起煮火锅。今晚一起讨论到现在,都忘了写总结。今天开始了计划了第一天。...
    朴菘菘麻麻阅读 133评论 0 0