AF
HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
AF
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.



corejava-programming: Happy number

3. A happy number is a number in which the eventual sum of the square of the digits of the number is equal to 1. Example: 28 28 = 2 square + 8 square = 4+64 = 68 68 = 6 square + 8 square = 36 + 64 = 100 100 = 1 square + 0 square + 0 square = 1+0+0 = 1 Hence, 28 is a happy number. Example 2 : 12 12 = 1 square + 2 square = 1 + 4 = 5 Hence, 12 is not a happy number. Write a java program happy.java to check if a given number is a happy number or not E.g Input : 28 Output: 28 is a happy number E.g input : 12 Output: 12 is not a happy number

corejava x 352
programming x 168
Posted On : 2017-01-22 09:21:30.0
profile Navin Kumar - anyforum.in Navin Kumar
600
up-rate
4
down-rate

Answers


import java.util.Scanner;

public class HappyNumber {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
Integer number=input.nextInt();
String num=number.toString();
Integer result=0;
for(int i=0;i<=1;i++){
if(num.length()>1){
for(int j=0;j<num.length();j++){
int digit=Integer.parseInt(Character.toString(num.charAt(j)));
result=result+digit*digit;
}
}
num=result.toString();
result=0;
}

System.out.print(number+" is ");

if(num.length()>1){
int sum=0;
for(int k=0;k<num.length();k++){
sum=sum+Integer.parseInt(Character.toString(num.charAt(k)));
}
if(sum==1){

}else{
System.out.print("not ");
}
}else if(Integer.parseInt(num)==1){
}else{
System.out.print("not ");
}
System.out.print("a Happy Number");
}
}

Posted On : 2017-01-24 00:24:52
Satisfied : 2 Yes  1 No
profile Rishi Kumar - anyforum.in Rishi Kumar
523188221600
Reply This Thread
up-rate
4
down-rate

Check this code and let me know if your conditions are satisfied or not.

import java.util.Scanner;
class HappyNumber
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int num=s.nextInt();
int hnum=num;
int sum=0,rem;
while(num>0)
{
rem=num%10;
sum+=rem*rem;
num=num/10;
if(num==0&&sum>9)
{
num=sum;
sum=0;
}
}
if(sum==1)
{
System.out.println(hnum+"is a happy number");
}
else
{
System.out.println(hnum+"is not a happy number");
}
}
}

Posted On : 2017-01-24 03:33:04
Satisfied : 18 Yes  2 No
profile Sudheer Kumar Javvadi - anyforum.in Sudheer Kumar Javvadi
0960
Reply This Thread
up-rate
5
down-rate



Post Answer
Please Login First to Post Answer: Login login with facebook - anyforum.in