Skip to content

Instantly share code, notes, and snippets.

@ajduke
Created June 27, 2013 12:05
Show Gist options
  • Save ajduke/5875934 to your computer and use it in GitHub Desktop.
Save ajduke/5875934 to your computer and use it in GitHub Desktop.
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class HarshadNumber {
public static void main(String[] args) {
for (int i = 0; i < 250; i++) {
// extract digits and sum i
int num = i;
List<Integer> digits = getDigits(num);
long l = sumOf(digits);
if (l != 0 && i % l == 0) {
System.out.print(" " + num);
}
}
}
private static long sumOf(List<Integer> digits) {
long l = 0L;
for (Integer integer : digits) {
l += integer;
}
return l;
}
private static List<Integer> getDigits(int num) {
List<Integer> integers = new ArrayList<>();
int currentNum = num;
int curDigit = 0;
int t = 10;
while ((curDigit = currentNum % t) > 0) {
integers.add(curDigit);
// sumOfDigits += curDigit;
currentNum /= t;
}
Collections.reverse(integers);
return integers;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment