Issue
The task is about so-called Good numbers.
If a number % of each of its digits == 0, the number is good.
The task is to count all the Good numbers in a given range. The range is A to B.
For example: 13 is not a good number because 13 % 3 != 0.
Also we have to skip if a digit is zero.
Another example 102 is a good number because 102 % 1 == 0 and 102 % 2 == 0.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] input = sc.nextLine().split(" ");
int[] arrInt = new int[input.length];
arrInt[0] = Integer.parseInt(input[0]);
arrInt[1] = Integer.parseInt(input[1]);
int counter = 0;
boolean isGoodNumber = false;
String s = "";
for (int i = arrInt[0]; i <= arrInt[1]; i++) {
s = Integer.toString(i);
for (int j = 0; j < s.length(); j++) {
if (s.charAt(j) == 0) {
continue;
}
int result = i / s.charAt(j);
if (result % 1 != 0) {
isGoodNumber = false;
break;
}
}
if (isGoodNumber) {
counter += 1;
}
isGoodNumber = true;
}
System.out.println(counter);
}
}
Solution
I have updated the code below
You were using character in your integer calculations for good numbers and not converting it back to int.
Also isGoodNumber was set to false initially as it should be set true
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] input = sc.nextLine().split(" ");
int[] arrInt = new int[input.length];
arrInt[0] = Integer.parseInt(input[0]);
arrInt[1] = Integer.parseInt(input[1]);
int counter = 0;
boolean isGoodNumber = true;
String s = "";
for (int i = arrInt[0]; i <= arrInt[1]; i++) {
s = Integer.toString(i);
for (int j = 0; j < s.length(); j++) {
if (s.charAt(j) - '0' == 0) {
continue;
}
if (i % (s.charAt(j) - '0') != 0) {
isGoodNumber = false;
break;
}
}
if (isGoodNumber) {
counter += 1;
}
isGoodNumber = true;
}
System.out.println(counter);
}
}
Answered By - shubhy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.