zoukankan      html  css  js  c++  java
  • 力扣(LeetCode) 9.回文数

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

    示例 1:

    输入: 121
    输出: true

    示例 2:

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

    示例 3:

    输入: 10
    输出: false

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

    思路 数字转化成字符串

    java版

    class Solution {
        public boolean isPalindrome(int x) {
            if(x<0) {
                return false;
            }else {
                String str = String.valueOf(x);
                StringBuilder s = new StringBuilder(str);
                
                if(s.reverse().toString().equals(str)) {
                    return true;
                }else {
                    return false;
                }
            }
        }
    }
    

    思路 构建数组,将数字每一位分布放进去,然后比较数组是否回文。

    int a=10; int s[a]={0}; 这样是不可以的。不可用变量作数组大小 ×

    int a=10; int s = (int)malloc(sizeof(int)*a); 推荐用这种方式取代 √

    C语言版

    bool isPalindrome(int x) {
        if(x<0) {
            return false;
        }else {
            int num = 0;//数字位数
            int xx = x;
            while(xx>0) {
               xx= xx/10;
                num++;
            }
            int *str = (int*)malloc(sizeof(int)*num);
            int i=0;
            while(x>0) {
                str[i++] = x%10;
                x = x/10;
            }
            for(i=0;i<num/2;i++) {
                int j = num-i-1;
                if(str[i]!=str[j]) {
                    return false;
                }
            }
            return true;
                   
        }
    }
    

    运行结果

  • 相关阅读:
    5.User Interface/Custom Components
    5.User Interface/Styles and Themes
    5.User Interface/Accessibility
    5.User Interface/Drag and Drop
    5.User Interface/Notifications
    5.User Interface/Dialogs
    Menu综合运用
    5.User Interface/ActionBar
    5.User Interface/Menu
    5.User Interface/Input Controls
  • 原文地址:https://www.cnblogs.com/lick468/p/10649407.html
Copyright © 2011-2022 走看看