Getting a wrong output using arraylists
You can use the following:
static List<Integer> sumDigPow(int a, int b) {
List<Integer> eureka = new ArrayList<Integer>(0);
String num;
int sum = 0, multi;
for (int i = a; i <= b; i++) {
num = String.valueOf(i);
for (int j = 0; j < num.length(); j++) {
multi = (int) Math.pow(Character.getNumericValue(num.charAt(j)), j + 1);
sum += multi;
}
if (sum == i) {
eureka.add(i);
}
sum = 0;
}
return eureka;
}
Explanation:
- You were not checking the second digit of the number.
- Loop over each character of the String
num
. - There is no need of the
digits
arraylist, you can just use the numeric value of the char.
The problem were those lines :
num = String.valueOf(i);
digits.add(num);
You did not split your number into digits. You were just putting your whole numbers into digits
list. Look at this code :
static List<Integer> sumDigPow(int a, int b) {
List<Integer> eureka = new ArrayList<Integer>();
List<String> digits;
String num;
int sum = 0, multi;
for (int i = a; i <= b; i++) {
num = String.valueOf(i);
digits = Arrays.asList(num.split(""));
for (int j = 0; j < digits.size(); j++) {
multi = (int) Math.pow(Integer.parseInt(digits.get(j)), j + 1);
sum += multi;
}
if (sum == i) eureka.add(i);
sum = 0;
}
return eureka;
}
I simply split your string number into digits using Arrays.asList(num.split(""))
. It outputs for a=1
, b=100
the list :
1
2
3
4
5
6
7
8
9
89