☀️前言☀️
本篇文章主要给大家讲一下方法使用的一些习题。
👦有缘,才相遇,你好!我是hgway_hxz
❤️热爱Java,希望结识更多的小伙伴一起交流
🎉欢迎大家:👍点赞 💬评论 ⭐收藏 💖关注
✉️如果有任何问题欢迎大家在评论区讨论或者私信我
✏️如果你的面前有阴影,那是因为你的背后有阳光
🔒1.打印0-999999中的自幂数
自幂数是一个n位自然数等于自身各个数位上数字的n次幂之和,例如153是一个三位数,各个数位的3次幂之和为153=13+53+33,所以153是十进制中的自幂数。我们拿153举例子
💡解题思路:
1.先知道自然数有几位数,除以10几次就是几位数,直到n为0
153 / 10 = 15
15 / 10 = 1
1 / 10 = 0
2.找到这个自然数的每一位数字的n次方,这个数每次%10可以得到尾数
153 % 10 = 3
153 / 10 = 15
15 % 10 = 5
15 / 10 = 1
1 % 10 = 1
1 / 10 = 0
Math.pow(底数, 指数),Math.pow(3, 3)就是求33
🔑代码:
public static void findNum(int n) {
for (int i = 1; i <= n; i++) {
int count = 0;//记录有几位数
int tmp = i;
while (tmp != 0) {
tmp = tmp / 10;
count++;
}
//此时count已经知道有几位数了,此时tmp = 0
tmp = i;
int sum = 0;//放各个数位上的count次幂之和
while (tmp != 0) {
sum += Math.pow(tmp%10, count);
tmp = tmp / 10;
}
if (sum == i) {
System.out.print(i + " ");
}
}
}
public static void main(String[] args) {
findNum(999999);
}
结果:
1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084 548834
Process finished with exit code 0
🔒2.打印100-999的水仙花数
🔑水仙花数也是自幂数,解题思路和上题一样,就直接放代码了
public static void main(String[] args) {
for (int i = 100; i <= 999; i++) {
int tmp = i;
int count = 0;
while (tmp != 0) {
tmp = tmp / 10;
count++;
}
tmp = i;
int sum = 0;
while (tmp != 0) {
sum += Math.pow(tmp % 10, count);
tmp = tmp / 10;
}
if (sum == i) {
System.out.print(i + " ");
}
}
}
结果:
153 370 371 407
Process finished with exit code 0
🔒3.写一个方法返回参数二进制中1的个数
💡解题思路:用按位与&来判断,返回这个数字的二进制中有几个1,以13举例子
13&1,二进制位为1,结果为1,二进制位为0,结果为0,13再无符号右移1位,统计结果为1的个数,最后13变成0时循环结束
🔑代码:
public static int numOfOne(int n) {
int count = 0;
while (n != 0) {
if ((n & 1) == 1) {
count++;
}
n = n >>> 1;
}
return count;
}
public static void main(String[] args) {
System.out.println(numOfOne(13));
System.out.println(numOfOne(-1));
}
优化:n & (n - 1)
13 = 0000 0000 0000 0000 0000 0000 0000 1101
12= 0000 0000 0000 0000 0000 0000 0000 1100
13 & 12 = 12
12 = 0000 0000 0000 0000 0000 0000 0000 1100
11 = 0000 0000 0000 0000 0000 0000 0000 1011
12 & 11 = 8
8 = 0000 0000 0000 0000 0000 0000 0000 1000
7 = 0000 0000 0000 0000 0000 0000 0000 0111
8 & 7 = 0
0 = 0000 0000 0000 0000 0000 0000 0000 0000
n每按位与一次就少一个1,按位与几次1就有几个,如果n变成了0说明一个1都没有了
代码:
public static int numOfOne(int n) {
int count = 0;
while (n != 0) {
n = n & (n-1);
count++;
}
return count;
}
结果:
3
32
Process finished with exit code 0
🔒4.编写代码模拟三次密码输入的场景
💡编写代码模拟三次密码输入的场景,最多能输入三次密码,密码正确,提示登录成功, 密码错误,可以重新输入,最多输入三次,三次均错,则提示退出程序.
🔑代码:
public static void login() {
Scanner scanner = new Scanner(System.in);
int count = 3;
while (count != 0) {
String password = scanner.nextLine();
if (password.equals("123456")) {
System.out.println("登陆成功!");
break;
} else {
count--;
System.out.println("密码错误!你还有 " + count + " 次机会");
}
}
}
public static void main(String[] args) {
//编写代码模拟三次密码输入的场景
login();
}