1、求一个整数,在内存当中存储时,二进制1的个数。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int count=0;
while(a!=0){
count++;
a=a&(a-1);
}
System.out.println(count);
}
}
2、求两个正整数的最大公约数
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int temp;
temp=a>b? b:a;
for(int i=temp;i>0;i--){
if(a%i==0&&b%i==0){
System.out.println(i);
break;
}
}
}
}
3、计算1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100 的值 。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double a=1;
double sum_1=0;
int flag=1;
for(double b=1;b<=100;b++) {
sum_1=sum_1+flag*(a/b);
flag=-flag;
}
System.out.println(sum_1);
}
}
4、求出0~999之间的所有“水仙花数”并输出。(“水仙花数”是指一个三位数,其各位数字的立方和确好等于该数本 身,如;153=1+5+3?,则153是一个“水仙花数“。)
mport java.util.Scanner;
import java.math.*;
public class Main {
public static void main(String[] args) {
double a = 0;
double b = 0;
double c = 0;
for (int i = 100; i < 1000; i++) {
a = Math.pow(i % 10, 3);
b = Math.pow(i / 10 % 10, 3);
c = Math.pow(i / 100, 3);
if (a + b + c == i) {
System.out.println(i);
}
}
}
}
5、完成猜数字游戏
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Random random = new Random();
int goal = random.nextInt(101);
System.out.print("请输入你猜的数字0-100:");
Scanner sc = new Scanner(System.in);
while(true) {
int a = sc.nextInt();
if (a < goal) {
System.out.println("你猜小了");
} else if (a == goal) {
System.out.println("你猜对了");
break;
} else if (a > goal) {
System.out.println("你猜大了");
}
}
}
}