深圳Java学习:Java面试经典算法题2
1.输入三个整数x,y,z,请把这三个数由小到大输出。
import java.util.*;
public class C{
public static void main(String[] args) {
int x=0, y=0, z=0;
Scanner scanner = new Scanner(System.in);
System.out.print(“输入第一个数字:”);
x = scanner.nextInt();
System.out.print(“输入第二个数字:”);
y = scanner.nextInt();
System.out.print(“输入第三个数字:”);
z = scanner.nextInt();
if(x > y) {
int t = x;
x = y;
y = t;
}
if(x > z) {
int t = x;
x = z;
z = t;
}
if(y > z) {
int t = y;
y = z;
z = t;
}
System.out.println( "三个数字由小到大排列为: "+x + " " + y + " " + z);
}
}
2.求1+2!+3!+…+20!的和
public class F{
public static void main(String[] args) {
long sum = 0;
long fac = 1;
for(int i=1; i<=20; i++) {
fac = fac * i;
sum += fac;
}
System.out.println(sum);
}
}
3.不使用中间变量,把两个变量的值互换
public class E{
public static void main(String[] args) {
int a = 10;
int b = 100;
a = a * b;
b = a / b;
a = a / b;
System.out.print(“a=” + a + " b=" + b);
}
}
4.一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在 第10次落地时,共经过多少米?第10次反弹多高?
public class K{
public static void main(String[] args) {
double h = 100, s = 100;
for (int i = 1; i < 10; i++) {
s = s + h;
h = h / 2;
}
System.out.println(“经过路程:” + s);
System.out.println(“反弹高度:” + h / 2);
}
}