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());
		}
	}

}

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