一、J1_21_1
我们都知道:1+2+3+ … + 49 = 1225。
现在要求你把其中两个不相邻的加号变成乘号,使得结果为 2015。
例如: 1+2+3+…+1011+12+…+2728+29+…+49 = 2015 就是符合要求的答案。
请你寻找所有可能的答案,并把前面的两个数字输出,如上面的就是输出(10 27)。
注意:使用循环或者递归实现。
代码如下:
public class Week01 {
public static void main(String[] args) {
// backInfo();
back();
}
public static void back() {
int temp = 0;
for (int i = 0; i < 50; i++) { // 穷举到50
for (int j = i; j < 50; j++) {
temp = 1225 - i * 2 - j * 2 - 2; // 减掉四个没有加上去的数,减2是a*2和b*2多出来的2
if (temp + i * (i + 1) + j * (j + 1) == 2015)// 筛选变成乘法之后的数
{
System.out.println(i + " " + j);
}
}
}
}
public static void backInfo() {
int sum = 2015;
for (int i = 1; i < 50; i++) {
sum -= i;
int count = 2015;
for (int j = 1; j < 50; j++) {
if (j == i) {
count -= i * (j + 1);
if (count == 0) {
System.out.println(i + " " + j);
}
j++;
} else {
count--;
}
}
}
}
}
二、J1_21_2
美国数学家维纳(N.Wiener)智力早熟,11 岁就上了大学。他曾在 1935~1936 年应邀来中国清华大学讲学。一次,他参加某个重要会议,年轻的脸孔引人注目。
于是有人询问他的年龄,他回答说:
“我年龄的立方是个 4 位数。我年龄的 4 次方是个 6 位数。这 10 个数字正好包含了从 0 到9 这 10 个数字,每个都恰好出现 1 次。”
请你编程计算,他当时到底有多年轻。
注意:使用循环实现,输出他的年龄在一行。
代码如下:
import java.util.HashSet;
public class Week02 {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
int a = (int) Math.pow(i, 3);
int b = (int) Math.pow(i, 4);
String str = Integer.toString(a) + Integer.toString(b);
if (Integer.toString(a).length() >= 4
&& Integer.toString(b).length() >= 6 && str.length() == 10) {
if (fun(str)) {
System.out.println(str);
System.out.println("年龄为:" + i);
}
}
}
}
public static boolean fun(String num) {// 这10个数字正好包含了从0到9这10个数字,每个都恰好出现1次。
// 判断是否重复,加入到set集合中的元素不能重复
HashSet<Character> set = new HashSet<Character>();// 比较相同
for (int i = 0; i < num.length(); i++) {
if (!set.add(num.charAt(i))) {// 如果重复返回false
return set.add(num.charAt(i));
}
}
return true;
}
}
三、J1_21_3
小米打算把图标设计成下面这样,但是他不知道几层最合适,于是想写个程序,打印出
不同层的图标,请你帮帮他。
—
———
—————
———————
注意:输入 n,打印 n 层高度的图标,如图是 4 层。
代码如下:
public class Week03 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("输入层数:");
int n = input.nextInt();
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
System.out.print("——");
}
System.out.println();
}
}
}