zoukankan      html  css  js  c++  java
  • 回文数

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

    如果输入是负数:return false;

    输入正数:如121, return true;

    第一遍写法直接判断数字第一位和最后一位是否相等:

    class Solution {
    public:
        bool isPalindrome(int x) {
            if(x <0) return false;
            int bits = 0;
            int t = x;
            while(t) {
                t = t / 10;
                bits += 1;
            }
            int left = x;
            int right = x;
            for(int i = 1; i <= bits/2; i++){
                cout << int(left / pow(10, bits-i)) << "," <<  right %10<< endl;
                if ( int(left / pow(10, bits-i)) != right %10 ){
                   // cout << left / pow(10, bits-i) << "," << right%10 << endl;
                    return false;
                } else {
                    left -= int(left/(pow(10, bits-i))) * pow(10,bits-i);
                    right = right /10;
                }
            }
            return true;   
        }
    };

    然后发现有更简单的代码:

    class Solution {
    public:
        bool isPalindrome(int x) {
            if(x <0) return false;
            //int bits = 0;
            long int ret = 0;
            int t = x;
            while(t != 0) {
                ret = ret*10 + t%10;
                t = t/10;
            }
            return ret == x;
    
        }
    };
    The Safest Way to Get what you Want is to Try and Deserve What you Want.
  • 相关阅读:
    动态规划_leetcode416
    动态规划_leetcode377
    基础整理
    super使用简介
    PHP替换指定字符串
    yii安装redis扩展(Windows)
    PHP多维数组去重
    git pull
    vue页面部署并移除url里面的#号
    fatal: refusing to merge unrelated histories(git pull)
  • 原文地址:https://www.cnblogs.com/Shinered/p/11221934.html
Copyright © 2011-2022 走看看