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

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

    虽然很简单,还是写一下题解吧。

    思路1. 首先判断负数和个位数是0但x不等于0的一定不是回文。然后翻转字符串的一半,判断另一半时候和翻转后的相等。注意:121这种奇数位结构。

     1 public class Solution {
     2     public bool IsPalindrome(int x) {
     3         //首先负数/大于0并且个位数为0肯定不是回文。
     4         if(x < 0) return false;
     5         if(x == 0) return true;
     6         if(x % 10 == 0) return false;
     7         int  tmp = 0;
     8         while( x > tmp ) {
     9             tmp = tmp * 10 + x % 10;
    10             x /= 10; 
    11         }
    12         return x == tmp || x == tmp / 10;
    13     }
    14 }
    View Code

    思路2.首先确定数字的位数,然后逐个判断第一位是否敌等于最后一位.....

     1 public class Solution {
     2     public bool IsPalindrome(int x) {
     3         if (x < 0){
     4             return false;
     5         }
     6         int a = 1;
     7         while (x / a >= 10){
     8             a *= 10;
     9         }
    10         while(x != 0){
    11             int left = x / a;
    12             int right = x % 10;
    13             if (left != right) return false;
    14             x = x % a;
    15             x /= 10;
    16             a /= 100;
    17         }
    18         return true;
    19     }
    20 }
    View Code
  • 相关阅读:
    PHP入门
    bootstrap框架
    jsp5 include forward param
    jsp4 Cookie
    网页定位导航
    jsp3 javabean
    Obsidian md安装闪退
    Excel 2016 Mac VBA 的变化 窗体消失
    Excel Mac 2016 调用 Applescript
    如何自学R
  • 原文地址:https://www.cnblogs.com/kanekiken/p/12596341.html
Copyright © 2011-2022 走看看