Computer Applications

A 'Happy Word' is defined as:

Take a word and calculate the word’s value based on position of the letters in English alphabet. On the basis of word’s value, find the sum of the squares of its digits. Repeat the process with the resultant number until the number equals 1 (one). If the number ends with 1 then the word is called a 'Happy Word'.

Write a program to input a word and check whether it a ‘Happy Word’ or not. The program displays a message accordingly.

Sample Input: VAT
Place value of V = 22, A= 1, T = 20
[Hint: A = 1, B = 2, ----------, Z = 26]

Solution:
22120 ⇒ 22 + 22 + 12 + 22 + 02 = 13
           ⇒ 12 + 32 = 10
           ⇒ 12 + 02 = 1

Sample Output: A Happy Word

Java

Java String Handling

41 Likes

Answer

import java.util.Scanner;

public class KboatHappyWord
{
    private static boolean isHappyNumber(long num) {
        long sum = 0;
        long n = num;
        do {
            sum = 0;
            while (n != 0) {
                int d = (int)(n % 10);
                sum += d * d;
                n /= 10;
            }
            n = sum;
        } while (sum > 6);
        
        return (sum == 1);
    }
    
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a word: ");
        String word = in.next();
        word = word.toUpperCase();
        String wordValueStr = "";
        int len = word.length();
        
        for (int i = 0; i < len; i++) {
            wordValueStr += String.valueOf(word.charAt(i) - 64); 
        }
        
        long wordValue = Long.parseLong(wordValueStr);
        boolean isHappy = isHappyNumber(wordValue);
        
        if (isHappy)
            System.out.println("A Happy Word");
        else
            System.out.println("Not a Happy Word");
    }
}

Variable Description Table

Program Explanation

Output

Answered By

13 Likes


Related Questions