算法机试题
在面试机试时,遇到一个算法题,当时没能写出来,最后是同学帮忙解决的。
这道题大致意思是:输入一个数,比如4,。这时会输出:
4 = 1 + 1 + 1 + 1
4 = 1 + 2 + 1
4 = 1 + 3
4 = 2 + 1 + 1
4 = 2 + 2
4 = 3 + 1
解决:
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
//提示输入
System.out.print("请输入:");
Scanner input = new Scanner(System.in);
int t = input.nextInt();
//求比i小的所有数
int[] sum = nums(t);
for (int i = 0; i < sum.length; i++) {
for (int j = 0; j < sum.length; j++) {
int temp = 0;
String str = t + "=" + sum[i] + "+" + sum[j];
temp += sum[i] + sum[j];
while(temp < t){
temp += 1;
str += "+" +1;
}
if(temp == t){
System.out.println(str);
}
}
}
}
//得到比输入数小的所有数
public static int[] nums(int i){
int[] temp = new int[i-1];
i -= (i-1);
for (int j = 0; j < temp.length; j++) {
temp[j] = i;
i++;
}
return temp;
}
}