Harshad Number Check in Java: Explanation & Practice

Check if a number is divisible by sum of its digits

Problem summary

A Harshad (or Niven) number is divisible by the sum of its digits. Check if the given number is Harshad.

Starter code

public class Main {
    public static void main(String[] args) {
        int number = 18; // Test case 1
        
        // Check if Harshad: 18 / (1+8) = 18/9 = 2
        // Print: Is Harshad: <true/false>
    }
}

Expected output and test cases

  • 18 % 9 = 0
    Is Harshad: true
  • 19 % 10 ≠ 0
    Is Harshad: false
  • 21 % 3 = 0
    Is Harshad: true

Hints

  1. Calculate sum of digits
  2. Check if number % sum == 0
  3. Handle edge case of sum being 0

Related Core Java Basics exercises

Practice all Core Java Basics exercises · Run this idea in the Java compiler