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

JAVA-简单面试题-算法

2016-09-04 11:29 295 查看
2给一个正整数 n,
找到若干个完全平方数(比如1, 4, 9, ... )使得他们的和等于
n。你需要让平方数的个数最少。

给出 n = 12, 返回
3 因为
12 = 4 + 4 + 4。

给出 n = 13, 返回
2 因为
13 = 4 + 9。

package Node_Swap;

import java.util.Scanner;

public class Search_Perfect_Square {

//	int the_start = (int) Math.sqrt(the_number);
static int[] starts;
static int[] starts_num;
int counts = 0;
public static void main(String[] args) {
// TODO 自动生成的方法存根
try{
Scanner scan = new Scanner(System.in);
System.out.println("请输入正整数N:");
int the_number = scan.nextInt();
if(the_number ==0){
System.out.println("0没有完全平方数");
}else if(the_number == 1){
System.out.println("1");
}
else{
int[] current_starts = new int[the_number];
int[] current_starts_num = new int[the_number];
int current_num = the_number;
int start = (int) Math.sqrt(the_number);
while(start > 0){
int i = 0;
int counts_num = 0;
starts = new int[the_number];
starts_num = new int[the_number];
Search_Perfect_Square sps = new Search_Perfect_Square();
sps.Search_Perfect_Square(the_number,start);
while(starts[i] > 0){
counts_num += starts_num[i];
i++;
}
if(current_num >= counts_num){
current_num = counts_num;
current_starts = starts;
current_starts_num = starts_num;
}
start--;
}

output_square(current_starts,current_starts_num);
}
}catch(NegativeArraySizeException e){
System.out.println("你输入了错误的数!");
}

}

public void Search_Perfect_Square(int the_start, int loop_start) {
// TODO 自动生成的构造函数存根
int the_other = 0;
starts[counts] = loop_start*loop_start;
starts_num[counts] = (int)the_start/(starts[counts]);
the_other = the_start - starts[counts] * starts_num[counts];
counts++;
loop_start--;
if(the_other == 0){
counts = 0;
}else{
Search_Perfect_Square(the_other,loop_start);
}
}
static void output_square(int[] output,int[] output_num){
int i = 0;
while(output[i]>0){
for(int j=0;j<output_num[i];j++){
System.out.print(output[i]+" ");
}
i++;
}
}

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