# My solution using hashSet. How can I optimize this further?

• My solution using hashSet.

``````public class Solution {
public boolean isHappy(int n) {

// Initialize a hashset.
HashSet<Integer> hashSet = new HashSet<Integer>();

// Loop the calculation until we find happy number of we learn that it loops
int temp = n;
while (true) {
temp = squareDigits(temp);
if (hashSet.contains(temp)) return false;
else if (temp == 1) return true;
}
}

private int squareDigits(int n) {

// Initialize useful variables (num array and length)
String str = Integer.toString(n);
int length = str.length();

// Initialize sum
int sum = 0;
int temp = 0;

// Convert to a list of digits, square it and add to sum
for (int i = 0; i < length; i++) {
temp = Integer.parseInt("" + str.charAt(i));
temp = temp * temp;
sum += temp;
}

// Return sum
return sum;
}
}``````

• This is not very efficient

``temp = Integer.parseInt("" + str.charAt(i));``

• Strings are slow; if you get the last digits mathematically it's a lot faster. If you're using the variable x:
while (x > 0){
int y = x % 10; // This gets the last digit of x
sum += y * y; // Add the square of the digit to the sum
x /= 10; // Divide x by 10 to truncate the last digit
}

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.