Problem:
Solution:
class Solution {
public:
// Since, we don't care about sorted order of keys, we should use unordered data structure instead of ordered(std::map or std::set -> store keys in // sorted order in binary search tree format: log n insertion, lookup time)
// And among unordered_map and unordered_set, we'll use unordered_set since we don't need values related to keys in this problem.
// unordered (set or map) use hashtables internally (not trees), so lookup/insertion time is constant. Drawback is: keys are not sorted as in BST.
bool check_num(int a, unordered_set<int> &set) {
if (set.find(a) != set.end())
return true;
set.insert(a);
return false;
}
bool isHappy(int n) {
int num = n;
int new_num = 0;
unordered_set<int> set;
while (1) {
while (n != 0) {
new_num += pow(n % 10, 2);
n /= 10;
}
if (new_num == 1)
return true;
else if (check_num(new_num, set))
return false;
n = new_num;
new_num = 0;
}
}
};
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
- 12 + 92 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
Solution:
class Solution {
public:
// Since, we don't care about sorted order of keys, we should use unordered data structure instead of ordered(std::map or std::set -> store keys in // sorted order in binary search tree format: log n insertion, lookup time)
// And among unordered_map and unordered_set, we'll use unordered_set since we don't need values related to keys in this problem.
// unordered (set or map) use hashtables internally (not trees), so lookup/insertion time is constant. Drawback is: keys are not sorted as in BST.
bool check_num(int a, unordered_set<int> &set) {
if (set.find(a) != set.end())
return true;
set.insert(a);
return false;
}
bool isHappy(int n) {
int num = n;
int new_num = 0;
unordered_set<int> set;
while (1) {
while (n != 0) {
new_num += pow(n % 10, 2);
n /= 10;
}
if (new_num == 1)
return true;
else if (check_num(new_num, set))
return false;
n = new_num;
new_num = 0;
}
}
};
No comments:
Post a Comment