## Sabre Holdings Interview Question for Java Developers

Country: India

Comment hidden because of low score. Click to expand.
0
of 0 vote

LeetCode 202. Happy Number

Comment hidden because of low score. Click to expand.
0
of 0 vote

something like this should be ok

``````public static void main(String[] args) {
var input = new Scanner(System.in);
System.out.print("Enter number <0 to exit> : ");
var n = input.nextInt();
while (n != 0) {
System.out.println(isHappy(n) ? 1 : 0);
System.out.print("Enter number <0 to exit> : ");
n = input.nextInt();
}
}

private static boolean isHappy(int n) {
var set = new HashSet<Integer>();
int computed;
do {
computed = 0;
while (n > 0) {
computed += square(n % 10);
n /= 10;
}
if (set.contains(computed)) break;
n = computed;
} while (computed != 1);
return computed == 1;
}

private static int square(int i) { return i * i; }``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

We can massively reduce the code by following this :
[ en.wikipedia.org/wiki/Happy_number ] and following that :

All unhappy numbers follow sequences that eventually reach the eight-number cycle

4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 → ...

Comment hidden because of low score. Click to expand.
0
of 0 vote

class HappyNumber {

static int numSquareSum(int n) {
int squareSum = 0;
while (n!= 0) {
squareSum += (n % 10) * (n % 10);
n /= 10;
}
return squareSum;
}

// method return true if n is Happy number
static boolean isHappynumber(int n) {
int slow, fast;
slow = fast = n;
do {
slow = numSquareSum(slow);
fast = numSquareSum(numSquareSum(fast));
} while (slow != fast);
return (slow == 1);
}

public static void main(String[] args) {
int n = 13;
if (isHappynumber(n))
System.out.println(n + " is a Happy number");
else
System.out.println(n + " is not a Happy number");
}
}

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````// Utility method to return sum of square of
// digit of n
int numSquareSum(int n)
{
int squareSum = 0;
while (n)
{
squareSum += (n % 10) * (n % 10);
n /= 10;
}
return squareSum;
}

//    method return true if n is Happy number
bool isHappynumber(int n)
{
int slow, fast;

//    initialize slow and fast by n
slow = fast = n;
do
{
//    move slow number by one iteration
slow = numSquareSum(slow);

//    move fast number by two iteration
fast = numSquareSum(numSquareSum(fast));

}
while (slow != fast);

//    if both number meet at 1, then return true
return (slow == 1);
}``````

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.