[Daily Blue Bridge] 47.17 Provincial Competition Java Group Real Question "Take Digits"

Hello, I am the little gray ape, a programmer who can write bugs!

Welcome everyone to pay attention to my column " Daily Blue Bridge ". The main function of this column is to share with you the real questions of the Blue Bridge Cup provincial competitions and finals in recent years, analyze the algorithm ideas, data structures and other content that exist in it, and help you learn To more knowledge and technology!

Title: Take the number of digits

There are many ways to find the k-th digit of an integer.

The following method is one.

public class Main {

	static int len(int x) {
		if (x<10) return 1;
		return len(x/10) + 1;
	}
	
//	取x的第k位数字
	static int f(int x,int k) {
		if(len(x)-k==0) return x%10;
		return _______________________;	//填空
	}
	
	public static void main(String[] args) {
		int x = 23513;
		System.out.println(f(x, 3));
	}

}

For the test data in the question, it should print 5.

Please analyze the source code carefully and add the missing code in the underlined part.

Note: Only submit the missing code, do not fill in any existing content or descriptive text.

Problem-solving ideas:

The main solution to this question is to understand the role of each function. According to the internal structure of the len() function, it can be judged that the role of the len() function is to read the length of each number, that is, how many bits there are. The function is to get the k-th digit of x, which can be judged from its return value. Only when the length of the number x is equal to the number of digits k, will the desired result be returned. At this time, what we have to do is actually think The solution can be solved by shortening the length of x.

Answer source code:

public class Year2017_Bt5 {

	static int len(int x) {
		if (x<10) return 1;
		return len(x/10) + 1;
	}
	
//	取x的第k位数字
	static int f(int x,int k) {
		if(len(x)-k==0) return x%10;
		return f(x/10, k);	//填空
	}
	
	public static void main(String[] args) {
		int x = 23513;
		System.out.println(f(x, 3));
	}

}

Sample output:

 

There is insufficient or those areas of improvement, but also hope that the message put forward a small partner, learn together!

Interested friends can follow the column!

Little Gray Ape will accompany you to make progress together!

Guess you like

Origin blog.csdn.net/weixin_44985880/article/details/115278803