---
title: "Write a Java Program to check if any number is a magic number or not."  
description: "Write a Java Program to check if any number is a magic number or not."  
author: "Mukul Goenka"  
published: 2021-11-22  
canonical: https://www.mindstick.com/interview/33842/write-a-java-program-to-check-if-any-number-is-a-magic-number-or-not  
category: "java"  
tags: ["c#", "java", "programming language"]  
reading_time: 3 minutes  

---

# Write a Java Program to check if any number is a magic number or not.

Write a Java Program to check if any number is a magic number or not. A number is said to be a magic number if after doing sum of digits in each step and in term doing sum of digits of that sum, the ultimate result (when there is only one digit left) is 1.

Example, consider the number:

Step 1: 163 => 1+6+3 = 10

Step 2: 10 => 1+0 = 1 => Hence 163 is a magic number

\

```
class HelloWorld {    public static void main(String[] args) {        int num = 163;         int sumOfDigits = 0;              if(isMagic(num)) {           System.out.println("Magic number");       }else {           System.out.println("Not magic number");       }   }   public static boolean isMagic(int num){       int sumOfDigits=0;       while (num > 0 || sumOfDigits > 9)        {            if (num == 0)            {                num = sumOfDigits;                sumOfDigits = 0;            }            sumOfDigits += num % 10;            num /= 10;        }     return sumOfDigits == 1;   }}
```

## Answers

### Answer by Mukul Goenka

Write a Java Program to check if any number is a magic number or not. A number is said to be a magic number if after doing sum of digits in each step and in term doing sum of digits of that sum, the ultimate result (when there is only one digit left) is 1.

Example, consider the number:

Step 1: 163 => 1+6+3 = 10

Step 2: 10 => 1+0 = 1 => Hence 163 is a magic number

\

```
class HelloWorld {    public static void main(String[] args) {        int num = 163;         int sumOfDigits = 0;              if(isMagic(num)) {           System.out.println("Magic number");       }else {           System.out.println("Not magic number");       }   }   public static boolean isMagic(int num){       int sumOfDigits=0;       while (num > 0 || sumOfDigits > 9)        {            if (num == 0)            {                num = sumOfDigits;                sumOfDigits = 0;            }            sumOfDigits += num % 10;            num /= 10;        }     return sumOfDigits == 1;   }}
```


---

Original Source: https://www.mindstick.com/interview/33842/write-a-java-program-to-check-if-any-number-is-a-magic-number-or-not

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
