JAVA-简单面试题-算法

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++;
		}
	}
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值