【Java】两道力扣算法题和do...while循环

一、练习:回文数

需求:给你一个整数 x 。
如果 x 是一个回文整数,打印 true ,否则,返回 false 。
解释:回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
例如,121 是回文,而 123 不是。

package com.itheima.test;

public class Test18 {
    public static void main(String[] args) {
        //分析:
        //1.定义变量记录整数
        int x = 12345;
        //把x做一个临时存储,用来最后进行判断
        int temp = x;
        //2.定义变量记录最终的结果(反过来的数字)
        int result = 0;
        //3.利用循环从右往左获取x中的数字并拼接到result当中
        //while
        while(x != 0){
            //获取到x最右边的数字
            int ge = x % 10;
            //获取一次数字之后,那么就要把当前最右边的数字给去掉
            x = x / 10;
            //拼接到result当中
            result = result * 10 + ge;
        }
        System.out.println(result == temp);



      /*  //1.如何获取到3
        int ge = x % 10;
        result = result + ge;
        System.out.println(result);

        //2.把十位2拼接到result里面
        int shi = x / 10 % 10;
        result = result * 10 + shi;
        System.out.println(result);//32

        //3.把百位拼接到result里面
        int bai = x / 100 % 10;
        result = result * 10 + bai;
        System.out.println(result);//321*/
    }
}

二、求商和余数

需求:给定两个整数,被除数和除数(都是正数,且不超过int的范围) 。
将两数相除,要求不使用乘法、除法和 % 运算符。
得到商和余数。

package com.itheima.test;

public class Test19 {
    public static void main(String[] args) {
        /*
        分析:
            被除数 / 除数 = 商 ... 余数

        int a = 100;
        int b = 10;

        100 - 10 = 90
        90 - 10 = 80
        80 - 10 = 70
        70 - 10 = 60
        ...
        10 - 10 = 0 (余数)

        */


        //1.定义变量记录被除数
        int dividend = 100;
        //2.定义变量记录除数
        int divisor = 37;
        //3.定义一个变量用来统计相减了多少次
        int count = 0;
        //3.循环 while
        //在循环中,不断的用被除数 - 除数
        //只要被除数 是大于等于除数的,那么就一直循环
        while(dividend >= divisor){
            dividend = dividend - divisor;
            //只要减一次,那么统计变量就自增一次
            count++;
        }
       //当循环结束之后dividend变量记录的就是余数
        System.out.println("余数为:" + dividend);
        //当循环结束之后,count记录的值就是商
        System.out.println("商为:" + count);
    }
}

三、do…while循环

语法和特点:先执行后判断

image-20240402172801328

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值