While scrolling through LinkedIn, I came across a question about Happy Numbers. I solved it, and it was quite interesting.
what is happy number π :
Examples :
Input: n = 19
Output: True
19 is Happy Number,
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
As we reached to 1, 19 is a Happy Number.
Input: n = 20
Output: False
package Interview_practice;
import java.util.HashSet;
import java.util.Scanner;
public class HappyNumber {
public static void main(String[] args) {
System.out.println("Enter Number To find happynumber :");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
if (happynum(num) == true) {
System.out.println("Happy number");
} else {
System.out.println("Not Happy number");
}
sc.close();
}
public static boolean happynum(int num) {
HashSet<Integer> seen = new HashSet<Integer>();// store and find repeated num
while (num != 1 && !seen.contains(num)) {
seen.add(num);
num = findhappy(num);
}
if (num == 1) {
return true;
} else {
return false;
}
}
public static int findhappy(int num) {
int total = 0;
while (num > 0) {
int n = num % 10;
total += n * n;
num = num / 10;
}
return total;
}
}
Output:
Enter Number To find happynumber :
19
Happy number π
Enter Number To find happynumber :
78
Not Happy number π₯²
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
package Afternoon;
public class Trapping_of_Rainwater {
public static void main(String[] args) {
int[] heigth = { 0, 4, 5, 1};
int[] left = new int[heigth.length];
int[] rigth = new int[heigth.length];
int n = findtrapWater(heigth, left, rigth);
System.out.println("Trapping_of_Rainwater :" + n + " units.");
}
private static int findtrapWater(int[] heigth, int[] left, int[] rigth) {
int max = 0;
for (int i = 0; i < heigth.length; i++) {
if (heigth[i] >= max) {
max = heigth[i];
}
left[i] = max;//0 4 5 5
}
max = 0;
for (int i = heigth.length - 1; i >= 0; i--) {
if (heigth[i] >= max) {
max = heigth[i];
}
rigth[i] = max;//5 5 5 1
}
int total = 0;
for (int i = 0; i < heigth.length; i++) {
int minHeigth = 0;
if (left[i] < rigth[i]) {
minHeigth = left[i];
} else {
minHeigth = rigth[i];
}
//heigth[i] 0 4 5 1
total += minHeigth - heigth[i];//0-0+4-4+5-5+1-1
}
return total;
}
}
Output:
Trapping_of_Rainwater :0 units.
Top comments (1)
The logic is ok ,but this specific array {0, 4, 5, 1} doesn't form any water. So the result is currently 0.
in this code you tried thisge tried likethe
| * * 5
| * 4 5
| * 4 5
| * 4 5
|__*_ 4___ 5_1_____
six * place have the water trap ..so six units of rainwater ...are u doing like this..am I correct??