1.求一个数字的二进制数有几个“1”:
在 Java 典例(1)中我们做到了这道例题,今天我们将方法优化,以下即为优化后源码:
public class TextDemo1 {
public static int number2(int num2) {
int count = 0;
while (num2 != 0) {
count++;
num2 = num2&(num2-1);
}
return count;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num2 = scanner.nextInt();
System.out.println(number2(num2));
}
}
运行结果如下(输入 10 和 -1 时):
2. 输出所有三位数的水仙花数:
/**
* @instruction: Created with IntelliJ IDEA.
* @Description:
* @author: Lixinwei
* @Date: 2018/11/4
* @Time: 13:50
*/
public class TextDemo4 {
public static void isDaffodil(int n1) {
System.out.println("①所有三位数的水仙花数:");
for (int f = 100; f < n1; f++) {
int i = f / 100;//求出百位数字
int m = (f % 100)/10;//求出十位数字
int n = ((f % 100) % 10);//求出个位数字
if (Math.pow(i,3)+Math.pow(m,3)+Math.pow(n,3) != f) {
//System.out.println(f+"是水仙花数");
continue;//三个位数的三次方和不等于此数字则跳出此次循环
}
System.out.println(f);
}
}
public static void main(String[] args) {
isDaffodil(1000);
}
}
运行结果如下:
3.判断一个int类型的数据是否为完数(完数: 6 → 因子:2,3,1. 他们的和是数字6)
import java.util.Scanner;
public class TextDemo4 {
public static boolean isPerfect(int n2) {
boolean isPerfect = false;
int sum = 0;
if (n2 ==0) {//0没有因子不是完数
return false;
}
for (int i = 1; i < n2; i++) {
if (n2 % i == 0) {//num从 [ 1-(num-1) ] 取余,余数为零则是该数的因子
sum += i;//将求出的因子相加得到sum
}
}
if (sum == n2) {//如果由因子相加得到的和sum值与num(输入的值)相等,则次数是完数
isPerfect = true;
}
return isPerfect;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("②判断一个int类型的数据是否为完数:");
System.out.println("请输入n2的值:");
int n2 = scanner.nextInt();
System.out.println(isPerfect(n2));
}
}
运行结果如下:
4.求a+aa+aaa+aaaa的和(例如:2+22+222+2222):
/**
* @instruction: Created with IntelliJ IDEA.
* @Description:
* @author: Lixinwei
* @Date: 2018/11/4
* @Time: 13:50
*/
public class TextDemo4 {
public static void fun2(int num, int n4) {//此处令num = 2, n4 = 4.
System.out.println("④求a+aa+aaa+aaaa的和:");
int a;
int sum=0;
a = num;//a=2
for (int i = 0; i < n4; i++) {
sum = (int)(sum + a * Math.pow(10,i) + a * Math.pow(10,i-1)+a * Math.pow(10,i-2)+a * Math.pow(10,i-3));
}
//n4等于多少就循环多少次-------------此处用到了强制转换将double类型强制转换为int类型
//第一次循环:sum = int ( sum + 2 * 10^ 0 + 2 * 10 ^ (-1) + 2 * 10 ^ (-2) + 2 * 10 ^ (-3) ).
//第二次循环:sum = int ( sum + 2 * 10^ 1 + 2 * 10 ^ (0) + 2 * 10 ^ (-1) + 2 * 10 ^ (-2) ).
//第三次循环:sum = int ( sum + 2 * 10^ 2 + 2 * 10 ^ 1 + 2 * 10 ^ 0 + 2 * 10 ^ (-1) ).
//第四次循环:sum = int ( sum + 2 * 10^ 3 + 2 * 10 ^ 2 + 2 * 10 ^ 1 + 2 * 10 ^ 0 ).
System.out.println(sum);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
fun2(2,4);
}
}
运行结果如下: