Skip to main content

Write a program to accept a word. Check if the word is a happy word or not.

/**
Suppose : VAT
ASCII code of V : 86 -64 => 22
ASCII code of A : 65 - 64 => 1
ASCII code of T : 84 - 64 => 20

Position of V: 22
Position of A: 1
Position of T: 20

Subtract the ascii value with 64,so we get the position values

To join the position values together, VAT => 22120

We need to perform this calculate
2*2+2*2+1*1+2*2+0*0 => 13
1*1+3*3 => 10
1*1+0*0 => 1

If we get 1 at the very end, then this is Happy Word
*/

import java.util.Scanner;
class HappyWord
{
 public static void main(String args[])
 {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter a word: ");
  String str = sc.next().toUpperCase();
  String num="";
  for(int i=0;i<str.length();i++)
  {
   char ch = str.charAt(i); //we get each every character
   int ascii = (int)ch;
   int pos=ascii-64;
   num=num+Integer.toString(pos);
  }
  System.out.println("The combined position is "+num);
  int n = Integer.parseInt(num); //converting string to integer
  int s=0;
  while(n>0 || s>9)
  {
   if(n==0)
   {
    n=s;
    s=0;
   }
   int r=n%10;
   s=s+r*r;
   n=n/10;
  }
  if(s==1)
   System.out.println(str+" is a happy word");
  else
   System.out.println("Not a happy word");
 }
}

Popular posts from this blog