Analysis of Java Written Exam Questions

  • topic

Find such a number: a number is equal to the addition of its decomposition items. The example number 28 can be decomposed into 1, 2, 4, 7, 14, 1+2+4+7+14=28. Similarly, the number 6 is decomposed into: 1, 2, 3, 1+2+3=6. Use the code to find all numbers within 1-500 that meet this condition.

  • Analysis
    What is a decomposition item: In short, it is divided by the decomposition item and equal to 0 without a remainder. It belongs to the decomposition item. For example, 28 is divided from 1 to 27 at once, but since the division to 28 is half in fact, there will be no decomposition items, so we only need temp / 2 + 1 when we loop. At this time, we can add the numbers that meet the requirements together, and then the number that meets the requirements is the same as the number itself.
  • Code
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);
	}
}

  • Topic 2

Write a program to list all files in a directory, including files in all subdirectories, and print out the total number of files

  • analysis

This is to recursively search through file.listFiles() and then count the number

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

}

Guess you like

Origin blog.csdn.net/qq_29897369/article/details/105181220