Java笔试题分析

  • 题目

找出这样的数字:一个数字等于它的各分解项相加。示例数字 28 可分解为 1、2、4、7、14,1+2+4+7+14=28。同样,数字 6 分解为:1、2、3,1+2+3=6。 用代码找出 1-500 以内的所有符合这样条件的数字。

  • 分析
    什么是分解项:简而言之就是本身除以分解项等于0 没有余数 就是属于它的分解项。比如28 从1到27 一次除,但是由于除到28一半其实后面肯定不会有分解项,所以我们循环的时候只需要temp / 2 + 1 就可以。这时候我们就可以将符合加到一起,然后在和本身比较 一样的就是符合要求的数字。
  • 代码实现
package com.dairuijie.demo.study;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @模块名:Day01
 * @包名:com.dairuijie.demo.study
 * @描述:DecompositionTerm.java
 * @版本:1.0
 * @创建人:drj
 * @创建时间:2020年3月28日下午10:45:07
 */
public class DecompositionTerm {
	/**
	 * 
	 */
	
	public static void main(String[] args) {
		int total = 0;
		List<Integer> list = new ArrayList<>();
		for (int i = 1; i <= 500; i++) {
			int temp = i;
			for (int j = 1; j <= temp / 2 + 1; j++) {
				if (temp % j == 0) {
					total = total + j;
				}
			}
			if(total == temp) {
				list.add(total);
			}
			System.err.println(String.format("数字:%s,分解项和%s", temp, total));
			total = 0;
		}
		System.err.println(list);
	}
}

  • 题目2

编写程序列出一个目录下所有的文件,包括所有子目录下的文件,并打印出 文件总数

  • 分析

这个就是递归寻找通过file.listFiles() 然后统计数量

  • 代码实现
package com.dairuijie.demo.study;

import java.io.File;

/**
 * 
 * @模块名:Day01
 * @包名:com.dairuijie.demo.study
 * @描述:FIndFileCount.java
 * @版本:1.0
 * @创建人:drj
 * @创建时间:2020年3月28日下午5:38:33
 */
public class FIndFileCount {
	
	public static Integer count = 0;
	
	public static void main(String[] args) {
		File file = new File("D:\\music");
		if(file.exists()) {
			findFile(file);
		}
		System.out.println("文件夹数量:" + count);
	}
	
	public static void findFile(File file) {
		File[] fs = file.listFiles();
		if(fs != null) {
			for(File f: fs) {
				findFile(f);
			}
		}else {
			count++;
			System.err.println(file.getName());
		}
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章