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。
找到若干个完全平方数(比如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 最简单菱形算法
- 又一种JSP实现的Java通用简单分页算法
- 求水仙花数简单算法java
- Java经典算法题目面试题经常出现的
- 匿名类~由一个貌似简单的java面试题所想到的···
- 一个基于Java的简单分组处理算法
- JAVA实现简单分组算法
- 查找""排序""简单数学计算" "简单算法"[Java实现](数据结构和算法)(复习)(持续更新
- 发布一个Java写的俄罗斯方块源码 算法简单(300行) 注释详细
- java面试题、考试题、简单题
- JSP实现的Java通用简单分页算法之三
- 发布一个Java写的俄罗斯方块源码 算法简单(300行) 注释详细
- 【技术收藏】enpaodelvzi编写:一个Java写的俄罗斯方块源码 算法简单(300行) 注释详细
- Java-流的简单使用:读取文件、写入文件(面试题:删除注释代码)
- Java基础部分-数组和简单算法
- 用友面试题答案 - java归并算法实现
- 最近在论坛里面看到一个算法题,简单描述确有些离奇(微软面试题)。。
- java经典算法面试题(1)
- 一点点最简单的java排序算法
- java面试题、考试题、简单题