1. 宝石与石头
题目来源
给你一个字符串 jewels 代表石头中宝石的类型,另有一个字符串 stones 代表你拥有的石头。 stones 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。字母区分大小写,因此 “a” 和 “A” 是不同类型的石头。
示例 1:
输入:jewels = “aA”, stones = “aAAbbbb”
输出:3
class Solution {
public:
int numJewelsInStones(string jewels, string stones) {
unordered_set<char> hash;
for (auto & c : jewels) hash.insert(c);
int ret = 0;
for (auto & c : stones){
if (hash.count(c) > 0) ++ret;
}
return ret;
}
};
2. 快乐数
题目来源
编写一个算法来判断一个数 n 是不是快乐数。
「快乐数」 定义为:
对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
如果这个过程 结果为 1,那么这个数就是快乐数。
如果 n 是 快乐数 就返回 true ;不是,则返回 false 。
示例 1:
输入:n = 19
输出:true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
class Solution {
public:
int happNum(int n){
int ret = 0;
while (n){
int k = n % 10;
ret += k * k;
n /= 10;
}
return ret;
}
bool isHappy(int n) {
int low = happNum(n), fast(happNum(happNum(n)));
// 如果是无线循环的话就是一个圈,使用快慢指针判断是否为环
while (low != fast){
low = happNum(low);
fast = happNum(happNum(fast));
}
return fast == 1;
}
};