首页 > 其他 > 详细

每日一题#02

时间:2019-03-30 17:00:46      阅读:131      评论:0      收藏:0      [点我收藏+]

题目

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

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

  

class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0)
return false; int last = 0; int head = 0; int count = 1000000000; while( count > 1 && x / count < 1) count /= 10; while( count > 0) { last = x % 10; // 最后一个数值 head = x / count; // 首个数值 if(last != head) return false; x = (x - last - (head * count)) / 10; count /= 100; } return true; } };

算法

个人想法:数字的首尾分别进行判断,首先用count计算出x占多少位(int型足够大),x%10得到末尾,x/count算出首位,进行循环  x = (x - last - (head * count)) / 10;

 

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0|| (x % 10 == 0 && x != 0))   return false ;
        if(x/10==0) return true;
    int left=x ;
    int right=0;
    int nums=0;
    if(x<0)
        return false;
    while(left>right){
    right=right*10+left%10;
    left/=10;
    }
    if(right/left>=10)   right=right/10;//如果为奇数
    if(left==right){
    return true;
    }
    else return false;
    return 0;
        
    }
};

 

官网解析:为了避免算法溢出,采取反转一半,例如1221,将后两位21反转(12)与前两位12进行比较,相同即为回文数。首先想到的是,当数字小于0时,不可能为回文数,首先进行排除  if(x<0) return false;  现在,让我们来考虑如何反转后半部分的数字。 对于数字 1221,如果执行 1221 % 10,我们将得到最后一位数字 1,要得到倒数第二位数字,我们可以先通过除以 10 把最后一位数字从 1221 中移除,1221 / 10 = 122,再求出上一步结果除以10的余数,122 % 10 = 2,就可以得到倒数第二位数字。如果我们把最后一位数字乘以10,再加上倒数第二位数字,1 * 10 + 2 = 12,就得到了我们想要的反转后的数字。 如果继续这个过程,我们将得到更多位数的反转数字。我们将原始数字除以 10,然后给反转后的数字乘上 10,所以,当原始数字小于反转后的数字时,就意味着我们已经处理了一半位数的数字。即可得到一个循环算法。

 来源:https://leetcode-cn.com/problems/palindrome-number/

每日一题#02

原文:https://www.cnblogs.com/shineko/p/10627869.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!