I am trying to make an integer to string to make slicing operation but the program doesn't gives me any answer it always gives the empty arraylist and While I see the modulus function simply returns the left but i want the modulus to return there.
public class My_first {
public static void main(String[] args) {
int left =1, right=22;
ArrayList<Integer> num = new ArrayList<>();
while(left<=right){
String number = Integer.toString(left);
int count =0;
for(int i=0;i<number.length();i++){
if(left % (int) number.charAt(i) == 0){
count++;
}
}
left++;
if (count >=number.length()){
num.add(left);
}
}
System.out.println(num);
}
}
Can anyone help me find out what is this issue here.. The output is to be {1,2,3,4,5,6,7,8,9,11,12,15,22}.
Thank you in advance!!!!!
Your code has a logical error in the modulus operation. The issue is with the expression (int) number.charAt(i)
. This line doesn't convert the character to its integer value, but rather to its ASCII value, which is not what you intend.
Try using Character.getNumericValue
instead:
import java.util.ArrayList;
public class MyFirst {
/**
* Finds all numbers between left and right (inclusive) where each digit of the number
* divides the number itself.
*
* @param left The starting number of the range.
* @param right The ending number of the range.
* @return An ArrayList containing numbers that meet the criteria.
*/
public static ArrayList<Integer> findDivisibleNumbers(int left, int right) {
ArrayList<Integer> numbers = new ArrayList<>();
while (left <= right) {
String number = Integer.toString(left);
int count = 0;
for (int i = 0; i < number.length(); i++) {
int digit = Character.getNumericValue(number.charAt(i));
if (digit != 0 && left % digit == 0) {
count++;
}
}
if (count == number.length()) {
numbers.add(left);
}
left++;
}
return numbers;
}
public static void main(String[] args) {
ArrayList<Integer> numbers = findDivisibleNumbers(1, 22);
System.out.println(numbers);
}
}
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
Other changes:
digit != 0
to handle the case where left
contains '0', as modulo by zero is undefined.An alternate approach using streams for the culture:
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public static ArrayList<Integer> findDivisibleNumbers(int left, int right) {
return IntStream.rangeClosed(left, right)
.filter(num -> {
String numberStr = Integer.toString(num);
return numberStr.chars()
.map(Character::getNumericValue)
.allMatch(digit -> digit != 0 && num % digit == 0);
})
.boxed()
.collect(Collectors.toCollection(ArrayList::new));
}