The number of blue bridge cup test questions algorithm training 1 (JAVA)

Problem description
  Enter a positive integer n, and determine how many times the number 1 should appear from 1 to n. For example, for the number 1123, 1 appears twice. For example, 15, from 1 to 15, there are a total of 8 1s.
  
Input format
  a positive integer n
output format
  an integer, representing the data that 1 appears.
  
Sample input
15
Sample output
8

Data size and agreement
  n does not exceed 30000

Solution:
  The first reaction to this question is to first convert the number into a string, and judge whether each number in the string is the string "1". If it is, add one to temp. code show as below:

import java.util.Scanner;

public class Main{
    
    
	public static void main(String[] args) {
    
    
		Scanner scanner=new Scanner(System.in);
		int n=scanner.nextInt();
		scanner.close();
		int temp=0;
		for(int i=1;i<=n;i++) {
    
    //从1循环到n
			String string=i+"";
			for(int j=0;j<string.length();j++) {
    
    //当是两位数及以上时,就要对每位上的数进行判断
				char a=string.charAt(j);	
				boolean status=(a+"").contains("1");
				if(status) {
    
    
					temp++;				
				}
			}
			
		}
		System.out.println(temp);
	}
}

Evaluation result:Evaluation results
  Although the result passed the evaluation, but I always felt that my method was not very good, so I went to find the way of the big guy. Sure enough, the boss's method is concise and clear.
Solution:
  The following code is mainly to judge whether the number 1 is included by performing the remainder and rounding operations of 10 for each number.
  The code is as follows (Address: https://blog.csdn.net/a1439775520/article/details/104214711):

import java.util.Scanner;

public class 一的个数 {
    
    
    public static void main(String[] args) {
    
    
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        //使用完输入流要及时得关闭,防止占内存
        sc.close();
 
        //先把所有得变量都声明了
        int count = 0,a,b;
        for (int i = 1; i <= n; i++) {
    
    
            //用一个变量代替,如果更改i就会更改循环
            a=i;
            //和水仙花数一样得方法,取最后一位,/10删除最后一位
            while (a!=0){
    
    
                b=a%10;
                if (b==1) count++;
                a/=10;
            }

        }
        System.out.println(count);
        }
}

Evaluation results:
Evaluation results

Guess you like

Origin blog.csdn.net/qq_43692768/article/details/108990096