一、练习:回文数
需求:给你一个整数 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循环
语法和特点:先执行后判断