Lanqiao Cup: Digitly increasing number (converted to char array version) (easy to understand)

topic

[Problem description]
   If any digit of a positive integer is not greater than the adjacent digit on the right, it is called a digit increasing number. For example, 1135 is a digit increasing number, and 1024 is not a digit increasing number.
Given a positive integer n, how many digits are increasing among the integers 1 to n?
[Input format]
   The first line of input contains an integer n.
[Output format] The
   output line contains an integer to indicate the answer.
[Sample input]
30
[Sample output]
   26
[Evaluation use case scale and convention]
   For 40% of evaluation use cases, 1 <= n <= 1000.
   For 80% of the test cases, 1 <= n <= 100000.
   For all measurement cases, 1 <= n <= 1000000.

Problem solving ideas

  Personal humble opinion: I didn't think of recursion when I wrote it, so when solving the problem, I converted the number to an array of char type for judgment. (Personally think it should be easier to understand than recursion)

Precautions

   1 to 9 do not require judgment

answer

  n = 1000    :219
  n = 100000   :2001
  n = 1000000 :5004

Code


import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        int n=scanner.nextInt();
        int count=0;
        for(int i=1;i<=n;i++){
    
    
            if(f(i)){
    
     //调用f
                count++;
            }
        }
        System.out.println(count);
    }

    public static boolean f(int i){
    
    
        if(i<10){
    
     //1到9不需要进行判断
            return true;
        }else{
    
    
            char []s =(i+"").toCharArray();//转换为char数组
            for(int j=0;j<s.length-1;j++){
    
     //判断
                if(s[j]>s[j+1]){
    
    
                    return false;
                }
            }
        }
        return true;
    }
}

Guess you like

Origin blog.csdn.net/qq_47168235/article/details/108908583