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

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

    示例 1:

    输入: 121
    输出: true
    示例 2:

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

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

    我的解法为:把数字转换为字符数组,然后用循环判断它是否为回文数。代码为:

    class Solution {
        public boolean isPalindrome(int x) {
            char[] str = String.valueOf(x).toCharArray();
            int low = 0, high = str.length - 1;
            while(low <= high){
                if(str[low] == str[high]){
                    low++;
                    high--;
                }
                else return false;
            }
            return true;
        }
    }
    不过在黑板墙上看到了更简洁的做法,不需要开辟新数组,直接将数组反转,回文就是反转之后两个数也要相等!!!很省事:
    class Solution {
        public boolean isPalindrome(int x) {
            if(x<0)
                return false;
            int rem=0,y=0;
            int quo=x;
            while(quo!=0){
                rem=quo%10;
                y=y*10+rem;
                quo=quo/10;
            }
            return y==x;
        }
    }
  • 相关阅读:
    网络编程-python实现-UDP(1.1.2)
    网络编程-python实现-socket(1.1.1)
    1-浮动布局
    1-解决java Scanner出现 java.util.NoSuchElementException
    1.激活函数
    A-交叉熵的使用
    matplotlib的学习16-animation动画
    matplotlib的学习15-次坐标轴
    matplotlib的学习14-图中图
    07-爬虫验证码破解实战
  • 原文地址:https://www.cnblogs.com/hddandelion/p/13819140.html
Copyright © 2011-2022 走看看