java判断一个整数是否为回文数(正数和倒数值相等),例如:121是回文数,122不是回文数。

 前面用计数法求出几位数 然后再分别求出每位的值

 public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入整数");
        int a = sc.nextInt();
        int count =0;
        if ( a==0 ){
            count =1;
        }else{
            int temp =a;
            while (temp!=0){
                temp=temp/10;
                count++;
            }
        }
//        System.out.println(count);
        int b=0;
        int temp =a;
        for ( int i = 0 ;i<count;i++){
            b=b * 10 + temp % 10;
            temp=temp/10;
       }
        if (a == b) {
            System.out.println(a + "是回文数");
        } else {
            System.out.println(a + "不是回文数");
        }
    }

后面的代码把值放到数组中 ,并判定除到最后是否等于得到每个的数字 (除的次数 和位数大致一致)

  public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个数");
        int n = sc.nextInt();
        ints(n);
        int [] arr = ints(n);
//        System.out.println(Arrays.toString(arr));
        boolean flag = true;
        for (int i = 0,j = arr.length-1; i < arr.length/2; i++,j--) {
            if (arr[i] == arr[j]) {
                flag = true;
            }
        }
            if (flag){
                System.out.println(n+"不是回文数");
            }else {
                System.out.println(n+"是回文数");
            }
    }
    public static int[]ints(int n){
        int[] arr = new int[n];
        int num=0;
        for(int i=0;n>0;){
            arr[num++]=n%10;
            n /=10;
        }
        return Arrays.copyOf(arr,num);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值