【算法与数据结构】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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晚安66

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值