【算法与数据结构】202、LeetCode快乐数

所有的LeetCode题解索引,可以看这篇文章——【算法和数据结构】LeetCode题解

一、题目

在这里插入图片描述
在这里插入图片描述

二、解法

  思路分析:先用一个dowhile循环计算整数各个位数字的平方和,然后在unordered_set里面插入n,如果插不进去说明进入循环了,直接return,反之当n==1时退出循环。
  程序如下

class Solution {
    
    
public:
	bool isHappy(int n) {
    
    
		unordered_set<int> s1;
		int lower = 0, result = 0;
		while (n !=1) {
    
    
			do		// 求整数每个位上的数字的平方和
			{
    
    
				lower = n % 10;	// 低位
				n = n / 10;		// 去掉最低位
				result = result + lower * lower;
			} while (n);	// 最后n为0
			n = result;
			result = 0;		// 清空result
			if (!s1.insert(n).second) return false;	// 如果插入失败那么说明出现重复数字,已经陷入无线循环了
		}
		return true;
	}
};

复杂度分析:

  • 时间复杂度: O ( l o g n ) O(logn) O(logn),使用unordered_set,底层用哈希表实现,增删、查询操作都是 O ( 1 ) O(1) O(1),但是计算下一个查找数result的时间成本是 O ( l o g n ) O(log n) O(logn)
  • 空间复杂度: O ( l o g n ) O(logn) O(logn)

三、完整代码

# include <iostream>
# include <unordered_set>
using namespace std;

class Solution {
    
    
public:
	bool isHappy(int n) {
    
    
		unordered_set<int> s1;
		int lower = 0, result = 0;
		while (n !=1) {
    
    
			do		// 求整数每个位上的数字的平方和
			{
    
    
				lower = n % 10;	// 低位
				n = n / 10;		// 去掉最低位
				result = result + lower * lower;
			} while (n);	// 最后n为0
			n = result;
			result = 0;		// 清空result
			if (!s1.insert(n).second) return false;	// 如果插入失败那么说明出现重复数字,已经陷入无线循环了
		}
		return true;
	}
};

int main() {
    
    
	int n = 19;
	Solution s1;
	bool result = s1.isHappy(n);
	cout << "result:" << result << endl;
	system("pause");
	return 0;
}

end

猜你喜欢

转载自blog.csdn.net/qq_45765437/article/details/131259621