简体   繁体   中英

Find the number of numbers where the sum of each number is d in numbers less than N

I wrote a code to find the number of numbers where the sum of each number is d from numbers less than N. Compilation was completed, and typing n and d succeeded. But after that, it doesn't work. Which part should I fix and how? `import java.util.Scanner;

public class Main {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    
    System.out.print("Enter the num1 : ");
     int n = input.nextInt();
    System.out.print("Enter the num2 : ");
     int d = input.nextInt();
    int res=0;
    int sum=0;
    
    for(int i=1; i<=n; i++) {
       sum = 0;
     while(i>0) {
       sum += i%10;
       i /=10;
       }
     if(sum==d) {
       res++;
       }
    }
    System.out.println(res);
}

}

The problem is in the for loop. In the body of the for loop, you are changing the variable i which should not be done. Here is the solution

for(int i=1; i<=n; i++) {
   sum = 0;
   int j = i;
   while(j>0) {
     sum += j%10;
     j /=10;
   }
   if(sum==d) {
     res++;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM