您的位置:首页 > 职场人生

java面试题10个箱子600个苹果

2012-07-01 17:19 260 查看
import java.util.Scanner;

public class Apple2 {

public static void main(String[] args) {

int apple = 0;
int[] box = new int[10];
int apples = 600;
for (int i = 0; i < box.length - 1; i++) {// 初始化每个箱子:放0个苹果

box[i] = apple;
apple = apple * 2;

}

box[9] = apples - apple;

int math = 0;// 想要的苹果个数

boolean lab = false;// 是否大于600
boolean lastbox = false;// 是否要最后一个箱子

while (lab == false) {

try {
System.out.println("请输入0-600之间的数字 ");
Scanner input = new Scanner(System.in);
math = input.nextInt();
if (math > 600) {
lab = false;
} else {
lab = true;
}
} catch (RuntimeException e) {

lab = false;
}

}

if (math > 511) {
math = math - 89;
lastbox = true;
}
String bin = Integer.toBinaryString(math);// 把整数转化成二进制数,每个位对应是否取第几个箱子
char[] bina = bin.toCharArray();
for (int i = 0; i < bina.length; i++) {

if ("1".equals(bina[i] + "")) {
System.out.print(bina.length - i + "号箱子    ");
}

}
if (lastbox == true)

{
System.out.print("10号箱子    ");
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息