Dear experts,
I am doing my assignment on finding how many numbers in N digit satisfy K requirement.
However, when i am testing the code, i could compile it but i couldn't execute it.
I am wondering if i made mistake in the
x = result + y; // add them together and return it.
as when i comment this out, my program is able to execute,though i didn't get the right output value
Please kindly enlighten me.
Logic of my codes (example):
N = 15, K = 3
When N = 1, result = 0 + (N%10)
= 0 + (1%10)
= 1
y = N/10
= 1/10
= 0
x = 1 + 0
= 1
return x = 1
if (sumOfDigits(1) == K)
noOfNoSatisfy ++;
----------------------------------------------------
In the case of above, noOfSatisfy still remains as 0
-----------------------------------------------------
When N = 12, result = 0 + (N%10)
= 0 + (12%10)
= 2
y = N/10
= 12/10
= 1
x = 1 + 2
= 3
return x = 3
if (sumOfDigits(3) == K)
noOfNoSatisfy ++;
----------------------------------------------------
In the case of above, noOfSatisfy increase and plus 1
-----------------------------------------------------
import java.util.*;
public class Digits {
public static int sumOfDigits(int x) {
int result =0;
int y =0;
//eg. Let x be 1
while(x>0){
// eg. 1 = 1 + (1%10);
result = result + (x%10); //take the last digit of x
// eg. 0 = 1/10
y = x/10; //take the first digit of x
// eg. 1 = 1 + 0
x = result + y; // add them together and return it.
}
//eg. return 1
return x;
}
public static void main(String[] args) {
int N, K, noOfNoSatisfy;
Scanner sc = new Scanner (System.in);
//eg. Let N be 1
N = sc.nextInt();//indicate Number
//eg. Let K be 1
K = sc.nextInt();//indicate requirement number
noOfNoSatisfy = 0; // to count how many time it matches with K (requirement number)
for (int i = 1; i <=N; i++){
if(sumOfDigits(i) == K){//eg. 1 == K
noOfNoSatisfy ++; // plus 1 to count
}
} System.out.println(noOfNoSatisfy); //print the number of count
}
}