Blue Bridge Cup: Sum (String Practice)

topic

[Problem description]
   Xiao Ming is very interested in the numbers containing 2, 0, 1, 9 in the digits. Such numbers from 1 to 40 include 1, 2, 9, 10 to 32, 39 and 40, 28 in total. They The sum is 574. May I ask, from 1 to 2019, what is the sum of all such numbers?
[Answer Submission]
   This is a question that fills in the blanks with the result, you only need to calculate the result and submit it. The result of this question is an integer. When submitting the answer, only fill in this integer. If you fill in the extra content, you will not be able to score

answer

  1905111

Code

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int sum=0;
        for(int i=1;i<=2019;i++){
    
    
            String str = i+"";
            if(str.contains("2")){
    
    
                sum=sum+i;
            }else if(str.contains("0")){
    
    
                sum=sum+i;
            }else if(str.contains("1")){
    
    
                sum=sum+i;
            }else if(str.contains("9")){
    
    
                sum=sum+i;
            }else{
    
    
                continue;
            }
        }
        System.out.print(sum);

    }
}

Ideas

   Convert the number to a string, and use the contains method of the string to determine whether it meets the conditions.

Guess you like

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