Last active
September 15, 2017 19:20
-
-
Save Aravin/4c289a2196eb4602ba5749c9a4df8f36 to your computer and use it in GitHub Desktop.
A C# program to find whether given number is Happy or Sad
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
namespace HappyAndSadNumbers | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
string input; | |
Console.WriteLine("Enter the number: "); | |
input = Console.ReadLine(); | |
// Converting string to character array | |
char[] arr = input.ToCharArray(); | |
// Calling Method & Printing Output | |
Console.WriteLine(HappyOrSad(input, arr)); | |
Console.ReadKey(); | |
} | |
public static string HappyOrSad(string input, char[] arr) | |
{ | |
int result = 0; | |
// Hashset to store ouput of each loop | |
HashSet<int> repNumber = new HashSet<int>(); | |
// If number is repeated, break the loop | |
while (!repNumber.Contains(result) ) | |
{ | |
int temp = 0; | |
repNumber.Add(result); | |
for (int i = 0; i < arr.Length; i++) | |
{ | |
// Converting character array to integer | |
temp += Convert.ToInt32(arr[i].ToString()) * Convert.ToInt32(arr[i].ToString()); | |
} | |
arr = temp.ToString().ToCharArray(); | |
result = temp; | |
} | |
return result == 1 ? "Happy" : "Sad"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment