Write a program to check the given number is magic or not.
Magic Number: Sum of every digit till the number becomes a single digit. If the single digit is 1 then the magic number
Example 1:
Input: num=1234
Output: Number is magic number
Approach
Java
public class MagicNumber {public static void main(String[] args) {int num = 1234;if (isMagic(num))System.out.println("Number is magic ");elseSystem.out.println("Not a magic number ");}private static boolean isMagic(int num) {// iterate till number is not a single digit numberwhile (num >= 10) {int temp = 0;while (num > 0) {temp += num % 10;num = num / 10;}num = temp;}// if number with single digit and it is 1// then it is magicif (num == 1)return true;// else not a magic numberreturn false;}}
C++
#include <bits/stdc++.h>using namespace std;//function to check for//magic numberbool isMagic(int num){//iterate till num is not a single digit numberwhile(num>=10){int temp=0;while(num>0){temp+=num%10;num=num/10;}num=temp;}//if num with single digit and it is 1//then it is magicif(num==1)return true;//else not a magic numberreturn false;}int main(){int num=1234;if(isMagic(num))cout<<"Number is magic ";elsecout<<"Not a magic number ";return 0;}
No comments:
Post a Comment