我正在尝试将整数转换为字符串以进行切片操作,但程序没有给我任何答案,它总是给出空数组列表,虽然我看到模数函数只是返回左侧,但我希望模数返回那里。
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);
}
}
任何人都可以帮我找出这是什么问题吗? 输出为 {1,2,3,4,5,6,7,8,9,11,12,15,22}。
提前谢谢您!!!!
您的代码在模数运算中存在逻辑错误。问题在于表达
(int) number.charAt(i)
。此行不会将字符转换为其整数值,而是转换为 ASCII 值,这不是您想要的。
尝试使用
Character.getNumericValue
代替:
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);
}
}
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
其他变化:
digit != 0
的检查,以处理 left
包含“0”的情况,因为以零为模未定义。您应该检查除以零(当数字为0时),然后您可以使用
Character.getNumericValue(char ch)
从char中获取数字。
尝试这个解决方案并告诉我。
import java.util.ArrayList;
public class MyFirst {
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++) {
int digit = Character.getNumericValue(number.charAt(i));
if (digit != 0 && left % digit == 0) {
count++;
}
}
if (count == number.length()) {
num.add(left);
}
left++;
}
System.out.println(num);
}
}
输出
[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]