经典算法50例
【题目1】有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,则每个月的兔子总数为多少。
function mainFun() {
for (let i = 1; i <= 20; i++) {
console.log(`${i}月兔子总数:${getEveryMonthNum(i)}`);
}
}
function getEveryMonthNum(month) {
if (month == 1 || month == 2) {
return 1;
} else {
return getEveryMonthNum(month - 1) + getEveryMonthNum(month - 2);
}
}
mainFun();
结果:
1月兔子总数:1只
2月兔子总数:1只
3月兔子总数:2只
4月兔子总数:3只
5月兔子总数:5只
6月兔子总数:8只
7月兔子总数:13只
8月兔子总数:21只
9月兔子总数:34只
10月兔子总数:55只
11月兔子总数:89只
12月兔子总数:144只
13月兔子总数:233只
14月兔子总数:377只
15月兔子总数:610只
16月兔子总数:987只
17月兔子总数:1597只
18月兔子总数:2584只
19月兔子总数:4181只
20月兔子总数:6765只
【题目2】判断1-100之间有多少个素数,并输出所有素数(素数的定义:一个大于1的自然数,除了1和它本身外,不能整除以其他自然数,换句话说就是该数除了1和它本身以外不再有其他的因数的数才是素数)。
function mainFun() {
let num = 0;
for (let i = 0; i <= 100; i++) {
let flog = true;
if (i === 0) continue;
for (let j = 2; j <= Math.sqrt(i); j++) {//Math.sqrt(i)求平方根
if (i % j === 0) flog = false;
}
if (flog) {
console.log(i);
num++;
}
}
console.log(`0-100之间所有素数个数:${num}。`);
}
mainFun();
1
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
0-100之间所有素数个数:26。
【题目3】打印出所有的水仙花数。所谓水仙花数,是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个水仙花数,因为153 = 1 ^ 3 + 5 ^ 3 + 3 ^ 3。
function mainFun() {
for (let i = 100; i <= 999; i++) {
const gw = i % 10;
const sw = parseInt(i / 10) % 10;
const bw = parseInt(i / 100);
if (i === Math.pow(gw, 3) + Math.pow(sw, 3) + Math.pow(bw, 3)) {
console.log(i);
}
}
}
mainFun();
【题目4】将一个正整数分解质因数。例如:输入90,打印出90 = 2 * 3 * 3 * 5。
function mainFun(arg) {
let num = arg, arr = [];
for (let i = 2; i <= Math.sqrt(arg); i++) {
if (arg % i === 0) {
arr.push(i);
arg /= i;
i--;
}
}
console.log(`${num} = ${arr.join(' * ')} * ${arg} `)
}
mainFun(90);
结果:
90 = 2 * 3 * 3 * 5
【题目5】利用条件运算符的嵌套来完成此题:90分及以上的同学用A表示,60~89分之间的用B表示,60分以下的用C表示。
function mainFun(arg) {
return arg >100 || arg < 0 ? 'Error' : arg >= 90 ? 'A' : arg < 60 ? 'C' : 'B';
}
console.log(mainFun(90));
结果
A
【题目6】输入两个正整数m和n,求其最大公约数和最小公倍数。
function mainFun(x, y) {
let m = x, n = y, greatestCommonDivisor = 0;
while (true) {
if ((m = m % n) === 0) {
greatestCommonDivisor = n;
break;
}
if ((n = n % m) === 0) {
greatestCommonDivisor = m;
break;
}
}
const leastCommonMultiple = x * y / greatestCommonDivisor;
return "最大公约数:" + greatestCommonDivisor + "\n最小公倍数:" + leastCommonMultiple;
}
console.log(mainFun(9, 2));
结果:
最大公约数:1
最小公倍数:18
【题目7】输入一行字符,分别统计出其中英文字母、空格、数字、中文和其它字符的个数。
function mainFun(arg) {
let space = 0, //空格
letter = 0, //字母
digit = 0, //数字
cn = 0,//中文
other = 0;//其他字符
const strs = arg.split('');
for (const str of strs) {
if (/\s/g.test(str)) space++;
else if (/[a-zA-Z]/g.test(str)) letter++;
else if (/\d/g.test(str)) digit++;
else if (/[\u4e00-\u9fa5]/g.test(str)) cn++;
else other++;
}
return `空格:${space}\n字母:${letter}\n数字:${digit}\n中文:${cn}\n其他字符:${other}`
}
console.log(mainFun('abCD $ 哈哈'));
结果:
空格:2
字母:4
数字:0
中文:2
其他字符:1
【题目8】求s = a + aa + aaa + aaaa + aa...a的值,其中a是一个数字,几个数相加由键盘控制。
function mainFun(a, n) {
let temp = a, sum = a;
for (let i = 1; i < n; i++) {
a = a * 10 + temp;
sum += a;
}
return sum;
}
console.log(mainFun(1, 3));
结果:
123
【题目9】一个数如果恰好等于它的因子之和,这个数就称为完数,例如6 = 1 + 2 + 3。编程找出1000以内的所有完数。
const mainFunc = () => {
for (let i = 1; i < 1000; i++) {
let sum = 0;
for (let j = 1; j <= i / 2; j++) {
if (i % j == 0) {
sum += j;
}
}
if (i == sum) {
console.log(i);
}
}
}
mainFunc();
结果:
6
28
496
【题目10】一球从100米高度自由落下,每次落地后反跳回原高度的一半再落下。求它在第10次落地时,共经过多少米,第10次反弹多高。
const mainFunc = () => {
let s = 0, h = 100;
for (let i = 1; i <= 10; i++) {
s += h;
h /= 2;
s += h;
}
console.log("经过路程:" + (s - h));
console.log("反弹高度:" + h);
}
mainFunc();
结果:
经过路程:299.609375
反弹高度:0.09765625
【题目11】有1、2、3、4四个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?
const mainFunc = () => {
let nums = [];
for (let a = 1; a <= 4; a++) {
for (let b = 1; b <= 4; b++) {
for (let c = 1; c <= 4; c++) {
if (a != b && b != c && c != a) {
nums.push("" + a + b + c);
}
}
}
}
console.log(nums, '\n数量:' + nums.length);
}
mainFunc();
结果:
[
'123', '124', '132', '134',
'142', '143', '213', '214',
'231', '234', '241', '243',
'312', '314', '321', '324',
'341', '342', '412', '413',
'421', '423', '431', '432'
]
数量:24
【题目12】企业发放的奖金根据利润提成,利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时,高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%;高于100万元时,超过100万元的部分按1%提成。从键盘输入当月利润I,求应发放奖金总数?
const mainFunc = (num) => {
let bonus = num > 10
? num > 20
? num > 40
? num > 60
? num > 100
? function100_(num)
: function60_100(num)
: function40_60(num)
: function20_40(num)
: function10_20(num)
: function_10(num);
console.log(bonus);
}
mainFunc(120);
function function_10(num) {
return num * 0.1;
}
function function10_20(num) {
return (num - 10) * 0.075 + function_10(10);
}
function function20_40(num) {
return (num - 20) * 0.05 + function10_20(20);
}
function function40_60(num) {
return (num - 40) * 0.03 + function20_40(40);
}
function function60_100(num) {
return (num - 60) * 0.015 + function40_60(60);
}
function function100_(num) {
return (num - 100) * 0.01 + function60_100(100);
}
结果:
4.15
【题目13】一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
package leif;
public class Test {
public static void main(String[] args) {
for (int i = -100; i <= 10000; i++) {
if (Math.sqrt(i + 100) % 1 == 0) {
if (Math.sqrt(i + 100 + 168) % 1 == 0) {
System.out.println(i);
}
}
}
}
}
【题目14】输入某年某月某日,判断这一天是这一年的第几天。
package leif;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String date = scanner.next();
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(date));
System.out.println(calendar.get(Calendar.DAY_OF_YEAR));
} catch (ParseException e) {
e.printStackTrace();
} finally {
scanner.close();
}
}
}
【题目15】输入三个整数x、y、z,请把这三个数由小到大输出。
package leif;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
int y = scanner.nextInt();
int z = scanner.nextInt();
int[] is = {x, y, z};
Arrays.sort(is);
System.out.println(Arrays.toString(is));
scanner.close();
}
}
【题目16】打印九九乘法表。
package leif;
public class Test {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " * " + i + " = " + (i * j) + "\t");
}
System.out.println();
}
}
}
【题目17】猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不过瘾,又多吃了一个。第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
package leif;
public class Test {
public static void main(String[] args) {
int peach = 1;
for (int i = 9; i >= 1; i--) {
peach = (peach + 1) * 2;
}
System.out.println(peach);
}
}
【题目18】两个乒乓球队进行比赛,各出三人,甲队为a、b、c三人,乙队为x、y、z三人,已抽签决定比赛名单。有人向队员打听比赛的名单,a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。
package leif;
public class Test {
public static void main(String[] args) {
char[] m = {'a', 'b', 'c'};
char[] n = {'x', 'y', 'z'};
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < n.length; j++) {
if ((m[i] == 'a' && n[j] == 'x') || (m[i] == 'a' && n[j] == 'y')) {
continue;
} else if ((m[i] == 'b' && n[j] == 'y') || (m[i] == 'b' && n[j] == 'z')) {
continue;
} else if ((m[i] == 'c' && n[j] == 'x') || (m[i] == 'c' && n[j] == 'z')) {
continue;
} else {
System.out.println(m[i] + " vs " + n[j]);
}
}
}
}
}
【题目19】打印出如下图案(菱形)
*
package leif;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt();
for (int row = 1; row <= i; row++) {
for (int col = 1; col <= Math.abs((i + 1) / 2 - row); col++) {
System.out.print(" ");
}
for (int col = 1; col <= i - 2 * Math.abs((i + 1) / 2 - row); col++) {
System.out.print("*");
}
System.out.println();
}
scanner.close();
}
}
【题目20】有一分数序列:2/1、3/2、5/3、8/5、13/8、21/13……求出这个数列的前20项之和。
package leif;
public class Test {
public static void main(String[] args) {
double sum = 0;
for (int i = 1; i <= 20; i++) {
sum += getNumerator(i) / getDenominator(i);
}
System.out.println(sum);
}
public static double getNumerator(int numerator) {
if (numerator == 1) {
return 2;
} else if (numerator == 2) {
return 3;
} else {
return getNumerator(numerator - 1) + getNumerator(numerator - 2);
}
}
public static double getDenominator(int denominator) {
if (denominator == 1) {
return 1;
} else if (denominator == 2) {
return 2;
} else {
return getNumerator(denominator - 1) + getNumerator(denominator - 2);
}
}
}
【题目21】求1! + 2! + 3! + … + 20!的和。
package leif;
public class Test {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 20; i++) {
sum += getFactorial(i);
}
System.out.println(sum);
}
public static int getFactorial(int number) {
if (number == 1) {
return 1;
} else {
return number * getFactorial(number - 1);
}
}
}
【题目22】利用递归方法求5!。
package leif;
public class Test {
public static void main(String[] args) {
System.out.println(getFactorial(5));
}
public static int getFactorial(int number) {
if (number == 1) {
return 1;
} else {
return number * getFactorial(number - 1);
}
}
}
【题目23】有五个人坐在一起,问第5个人的岁数,他说比第4个人大两岁,问第4个人的岁数,他说比第3个人大两岁,问第三个人的岁数,他说比第2个人大两岁,问第2个人的岁数,他说比第1个人大两岁,最后问第1个人,他说是10岁。请问第五个人多大?
package leif;
public class Test {
public static void main(String[] args) {
int age = 10;
for (int i = 4; i >= 1; i--) {
age +=2;
}
System.out.println(age);
}
}
【题目24】输入一个不多于5位的正整数,求它是几位数并逆序打印出各位数字。
package leif;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i = 10000;
while ((i = scanner.nextInt()) >= 10000 || i <= 0) {
System.out.println("输入一个不多于5位的正整数");
}
StringBuilder stringBuilder = new StringBuilder(i + "");
System.out.println(stringBuilder.length());
System.out.println(stringBuilder.reverse());
scanner.close();
}
}
【题目25】输入一个5位数,判断它是不是回文数。即个位与万位相同、十位与千位相同。
package leif;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i = 0;
while ((i = scanner.nextInt()) > 99999 || i < 10000) {
System.out.println("输入一个5位数");
}
StringBuilder stringBuilder = new StringBuilder(i + "");
System.out.println(stringBuilder.toString().equals(stringBuilder.reverse().toString()) ? "是回文数" : "不是回文数");
scanner.close();
}
}
【题目26】请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母。
package leif;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入第一个字母:");
String letter1 = scanner.next();
switch (letter1) {
case "m":
case "M":
System.out.println("星期一");
break;
case "t":
case "T":
System.out.print("请输入第二个字母:");
String letter2 = scanner.next();
switch (letter2) {
case "u":
case "U":
System.out.println("星期二");
break;
case "h":
case "H":
System.out.println("星期四");
break;
default:
System.out.println("Error");
break;
}
break;
case "w":
case "W":
System.out.println("星期三");
break;
case "f":
case "F":
System.out.println("星期五");
break;
case "s":
case "S":
System.out.print("请输入第二个字母:");
String letter3 = scanner.next();
switch (letter3) {
case "a":
case "A":
System.out.println("星期六");
break;
case "u":
case "U":
System.out.println("星期日");
break;
default:
System.out.println("Error");
break;
}
break;
default:
System.out.println("Error");
break;
}
scanner.close();
}
}
【题目27】求100之内的素数。
package leif;
public class Test {
public static void main(String[] args) {
label: for (int i = 2; i < 100; i++) {
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) {
continue label;
}
}
System.out.println(i);
}
}
}
【题目28】对10个数进行排序。
package leif;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] is = new int[10];
for (int i = 0; i < is.length; i++) {
is[i] = (int) (Math.random() * 100 + 1);
}
System.out.println(Arrays.toString(is));
Arrays.sort(is);
System.out.println(Arrays.toString(is));
}
}
【题目29】求一个3*3矩阵对角线元素之和。
package leif;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[][] iss = new int[3][3];
for (int i = 0; i < iss.length; i++) {
for (int j = 0; j < iss[i].length; j++) {
iss[i][j] = (int) (Math.random() * 100 + 1);
}
}
System.out.println(Arrays.deepToString(iss));
int sum = 0;
for (int i = 0; i < iss.length; i++) {
for (int j = 0; j < iss[i].length; j++) {
if (i == j) {
sum += iss[i][j];
}
}
}
System.out.println(sum);
}
}
【题目30】有一个已经排好序的数组,现输入一个数,要求按原来的规律将它插入数组中。
package leif;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Integer[] is = new Integer[10];
for (int i = 0; i < is.length; i++) {
is[i] = (int) (Math.random() * 100 + 1);
}
System.out.println(Arrays.toString(is));
Arrays.sort(is);
System.out.println(Arrays.toString(is));
Integer[] newIs = new Integer[is.length + 1];
System.arraycopy(is, 0, newIs, 0, is.length);
newIs[newIs.length - 1] = scanner.nextInt();
boolean isASC = false;
for (int i = 0; i < is.length; i++) {
if (is[i] == is[i + 1]) {
continue;
}
if (is[i] < is[i + 1]) {
isASC = true;
}
break;
}
if (isASC) {
Arrays.sort(newIs);
} else {
Arrays.sort(newIs, new Comparator<Integer>() {
@Override
public int compare(Integer i1, Integer i2) {
return i2 - i1;
}
});
}
System.out.println(Arrays.toString(newIs));
scanner.close();
}
}
【题目31】将一个数组逆序输出。
package leif;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] is = new int[10];
for (int i = 0; i < is.length; i++) {
is[i] = (int) (Math.random() * 100 + 1);
}
System.out.println(Arrays.toString(is));
for (int i = is.length - 1; i >= 0; i--) {
System.out.print(is[i] + " ");
}
}
}
【题目32】取一个整数a从右端开始的4~7位。
package leif;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt();
String string = String .valueOf(i);
System.out.println(string.substring(string.length() - 7, string.length() - 4 + 1));
scanner.close();
}
}
【题目33】打印出杨辉三角形。
package leif;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numRows = scanner.nextInt();
List<List
for (int row = 0; row < numRows; row++) {
List<Integer> colList = new ArrayList<Integer>();
for (int col = 0; col <= row; col++) {
if (col == 0 || row == col) {
colList.add(1);
} else {
colList.add(rowList.get(row - 1).get(col) + rowList.get(row - 1).get(col - 1));
}
}
rowList.add(colList);
}
for (List<Integer> iList : rowList) {
System.out.println(iList);
}
scanner.close();
}
}
【题目34】输入3个数a、b、c,按大小顺序输出。
package leif;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] is = new int[3];
is[0] = scanner.nextInt();
is[1] = scanner.nextInt();
is[2] = scanner.nextInt();
Arrays.sort(is);
System.out.println(Arrays.toString(is));
scanner.close();
}
}
【题目35】输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。
package leif;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] is = new int[10];
for (int i = 0; i < is.length; i++) {
is[i] = (int) (Math.random() * 100 + 1);
}
System.out.println(Arrays.toString(is));
int maxIndex = 0;
int minIndex = 0;
for (int i = 0; i < is.length; i++) {
if (is[i] > is[maxIndex]) {
maxIndex = i;
}
if (is[i] < is[minIndex]) {
minIndex = i;
}
}
if (maxIndex != 0) {
is[0] = is[0] ^ is[maxIndex];
is[maxIndex] = is[0] ^ is[maxIndex];
is[0] = is[0] ^ is[maxIndex];
}
if (minIndex != is.length - 1) {
is[is.length - 1] = is[is.length - 1] ^ is[minIndex];
is[minIndex] = is[is.length - 1] ^ is[minIndex];
is[is.length - 1] = is[is.length - 1] ^ is[minIndex];
}
System.out.println(Arrays.toString(is));
}
}
【题目36】有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数。例:1、2、3、4、5后移动2个位置变成:4、5、1、2、3。
package leif;
import java.util.LinkedList;
import java.util.Queue;
public class Test {
public static void main(String[] args) {
Queue
int n = (int) (Math.random() * 10 + 1);
System.out.println(n);
for (int i = 0; i < n; i++) {
iQueue.offer((int) (Math.random() * 100 + 1));
}
System.out.println(iQueue);
int m = (int) (Math.random() * 10 + 1);
System.out.println(m);
for (int i = 0; i < m; i++) {
iQueue.offer(iQueue.poll());
}
System.out.println(iQueue);
}
}
【题目37】约瑟夫环:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。问最后留下的是原来的第几号。
package leif;
import java.util.LinkedList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List
int n = (int) (Math.random() * 10 + 1);
System.out.println(n);
for (int i = 1; i <= n; i++) {
iList.add(i);
}
int k = (int) (Math.random() * 10 + 1);
System.out.println(k);
int m = (int) (Math.random() * 10 + 1);
System.out.println(m);
while (iList.size() > 1) {
System.out.println(iList);
k = (k + m - 1) % n;
if (k == 0) {
k = iList.size();
}
iList.remove(k - 1);
n -= 1;
}
System.out.println(iList);
}
}
【题目38】编写一个方法求一个字符串的长度。
package leif;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(function(scanner.nextLine()));
scanner.close();
}
public static int function(String s) {
return s.length();
}
}
【题目39】编写一个方法,当n为偶数时,调用方法求1/2 + 1/4 + … + 1/n,当n为奇数时,调用方法求1/1 + 1/3 + … + 1/n。
package leif;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(function(scanner.nextInt()));
scanner.close();
}
public static double function(int n) {
double sum = 0;
if (n % 2 == 0) {
for (int i = 2; i <= n; i += 2) {
sum += 1.0 / i;
}
} else {
for (int i = 1; i <= n; i += 2) {
sum += 1.0 / i;
}
}
return sum;
}
}
【题目40】字符串排序。
package leif;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Test {
public static void main(String[] args) {
Random random = new Random();
List
for (int i = 1; i <= 10; i++) {
StringBuilder stringBuilder = new StringBuilder();
for (int j = 1; j <= 10; j++) {
stringBuilder.append((char) random.nextInt(128));
}
sList.add(stringBuilder.toString());
}
System.out.println(sList);
Collections.sort(sList);
System.out.println(sList);
}
}
【题目41】海滩上有一堆桃子,五只猴子来分。第一只猴子把这堆桃子凭据分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份;第二只猴子把剩下的桃子又平均分成五份,又多了一个,它同样把多的一个扔入海中,拿走了一份。第三、第四、第五只猴子都是这样做的,问海滩上原来最少有多少个桃子?
package leif;
public class Test {
public static void main(String[] args) {
int sum = 6;
for (int i = 4; i >= 1; i--) {
sum = sum * 5 + 1;
}
System.out.println(sum);
}
}
【题目42】已知809 * ?? = 800 * ?? + 9 * ??,其中??代表的两位数,8 * ??的结果为两位数,9 * ??的结果为3位数。求??代表的两位数及809 * ??后的结果。
package leif;
public class Test {
public static void main(String[] args) {
for (int i = 12; i <= 12; i++) {
if (809 * i == 800 * i + 9 * i) {
System.out.println(i + " " + (809 * i));
}
}
}
}
【题目43】求0~7所能组成的奇数个数(数字不能重复)。
package leif;
public class Test {
public static void main(String[] args) {
int sum = 4 * 6;
for (int i = 0; i < 6; i++) {
sum *= 6 - i;
}
System.out.println(sum);
}
}
【题目44】哥德巴赫猜想:证明一个大于2的偶数总能表示为两个素数之和。
package leif;
public class Test {
public static void main(String[] args) {
for (int n = 2; n <= 100; n += 2) {
for (int i = 2; i <= n - 2; i++) {
if (function(i)) {
if (function(n - i)) {
System.out.println(n + " = " + i + " + " + (n - i));
}
}
}
}
}
public static boolean function(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
【题目45】判断一个素数能把几个9整除, 如999999 % 7 = 0。
package leif;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
label: for (int i : function()) {
StringBuilder stringBuilder = new StringBuilder("9");
while (true) {
long l = 0L;
try {
l = Long.valueOf(stringBuilder.toString());
} catch (NumberFormatException e) {
System.out.println(i + " NumberFormatException");
continue label;
}
if (l % i == 0) {
System.out.println(stringBuilder + " % " + i + " = 0");
continue label;
}
stringBuilder.append(9);
}
}
}
public static List<Integer> function() {
List<Integer> iList = new ArrayList<Integer>();
label: for (int i = 2; i <= 100; i++) {
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) {
continue label;
}
}
iList.add(i);
}
System.out.println(iList);
return iList;
}
}
【题目46】两个字符串连接。
package leif;
public class Test {
public static void main(String[] args) {
String s1 = "1";
long time = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
s1 = s1 + "1";
}
System.out.println("加号所花费的时间:" + (System.currentTimeMillis() - time));
String s2 = "2";
time = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
s2.concat("2");
}
System.out.println("cancat方法所花费的时间:" + (System.currentTimeMillis() - time));
StringBuilder stringBuilder = new StringBuilder("3");
time = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
stringBuilder.append("3");
}
System.out.println("append方法所花费的时间:" + (System.currentTimeMillis() - time));
}
}
【题目47】读取7个数(1~50)的整数值,每读取一个值,程序打印出该值个数的*。
package leif;
public class Test {
public static void main(String[] args) {
for (int i = 1; i <= 7; i++) {
int random = (int) (Math.random() * 50 + 1);
System.out.println(random);
for (int r = 1; r <= random; r++) {
System.out.print("*");
}
System.out.println();
}
}
}
【题目48】某个公司采用公用电话传递数据,数据是四位的整数,在传递过程中是加密的,加密规则如下:每位数字都加上5,然后用和除以10的余数代替该数字,再将第一位和第四位交换,第二位和第三位交换。
package leif;
public class Test {
public static void main(String[] args) {
int i = (int) (Math.random() * 9000 + 1000);
System.out.println(i);
int a = i / 1000;
int b = i / 100 % 10;
int c = i / 10 % 10;
int d = i % 10;
System.out.println("" + (d + 5) % 10 + (c + 5) % 10 + (b + 5) % 10 + (a + 5) % 10);
}
}
【题目49】计算字符串中子串出现的次数。
package leif;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String s1 = scanner.nextLine();
System.out.println("请输入要查找的子字符串:");
String s2 = scanner.nextLine();
Pattern pattern = Pattern.compile(s2, Pattern.CANON_EQ);
Matcher matcher = pattern.matcher(s1);
int counter = 0;
while (matcher.find()) {
counter++;
}
System.out.println(s2 + "在" + s1 + "出现的次数为:" + counter);
scanner.close();
}
}
【题目50】有2个学生,每个学生有3门课的成绩,从磁盘文件中分别读入每个学生的学号、姓名和三门课成绩,计算出每个学生的总成绩,把原有的数据和计算出的数据输出到磁盘文件中。
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Test {
public static void main(String[] args) {
List
File file = new File("C:\Users\Administrator\Desktop\test50.xml");
SAXReader saxReader = new SAXReader();
saxReader.setEncoding("UTF-8");
try {
Document document = saxReader.read(file);
parserXML(document, studentList);
System.out.println(studentList);
} catch (DocumentException e) {
e.printStackTrace();
}
OutputFormat outputFormat = OutputFormat.createPrettyPrint();
outputFormat.setEncoding("UTF-8");
XMLWriter xmlWriter = null;
try {
FileWriter fileWriter = new FileWriter("C:\\Users\\Administrator\\Desktop\\newTest50.xml");
xmlWriter = new XMLWriter(fileWriter, outputFormat);
Document document = DocumentHelper.createDocument();
createXML(document, studentList);
xmlWriter.write(document);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (xmlWriter != null) {
try {
xmlWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void parserXML(Document document, List<Student> studentList) {
Element studentsElement = document.getRootElement();
List<Element> studentElementList = studentsElement.elements("student");
if (studentElementList != null) {
for (Element studentElement : studentElementList) {
Student student = new Student();
Attribute idAttribute = studentElement.attribute("id");
if (idAttribute != null) {
student.setId(Integer.valueOf(idAttribute.getText()));
}
Element nameElement = studentElement.element("name");
if (nameElement != null) {
student.setName(nameElement.getText());
}
double totalScore = 0;
Element subjectsElement = studentElement.element("subjects");
if (subjectsElement != null) {
List<Element> subjectElementList = subjectsElement.elements("subject");
if (subjectElementList != null) {
for (Element subjectElement : subjectElementList) {
Subject subject = new Subject();
Attribute nameAttribute = subjectElement.attribute("name");
if (nameAttribute != null) {
subject.setName(nameAttribute.getText());
}
Element scoreElement = subjectElement.element("score");
if (scoreElement != null) {
double score = Double.valueOf(scoreElement.getText());
subject.setScore(score);
totalScore += score;
}
student.addToSubjectList(subject);
}
}
}
student.setTotalScore(totalScore);
studentList.add(student);
}
}
}
public static void createXML(Document document, List<Student> studentList) {
Element studentsElement = document.addElement("students");
for (Student student : studentList) {
Element studentElement = studentsElement.addElement("student");
studentElement.addAttribute("id", String.valueOf(student.getId()));
studentElement.addElement("name").setText(student.getName());
Element subjectsElement = studentElement.addElement("subjects");
for (Subject subject : student.getSubjectList()) {
Element subjectElement = subjectsElement.addElement("subject");
subjectElement.addAttribute("name", subject.getName());
subjectElement.addElement("score").setText(String.valueOf(subject.getScore()));
}
studentElement.addElement("totalScore").setText(String.valueOf(student.getTotalScore()));
}
}
}
class Student {
private int id;
private String name;
private List
private double totalScore;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Subject> getSubjectList() {
return subjectList;
}
public void addToSubjectList(Subject subject) {
subjectList.add(subject);
}
public double getTotalScore() {
return totalScore;
}
public void setTotalScore(double totalScore) {
this.totalScore = totalScore;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", subjectList=" + subjectList + ", totalScore=" + totalScore + "]";
}
}
class Subject {
private String name;
private double score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public String toString() {
return "Subject [name=" + name + ", score=" + score + "]";
}
}