要求: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

  • 1*1 + 9*9 = 82
  • 8*8 + 2*2= 68
  • 6*6 + 8*8= 100
  • 1*1 + 0 + 0= 1

题目要求对任意一个正整数,不断计算各个数位上数字的平方和,若最终收敛为1,则该数字为happy number,否则程序可能从某个数开始陷入循环。这道题目我们只用根据规则进行计算,并使用图来存储已经出现过的数字即可。

class Solution {
public:
unordered_map<int, int> path;//使用图来存储每个计算结果
bool isHappy(int n) {
int result=0;
int key=n;
while (n) {//按照规则计算,计算key的result
int temp = n%10;
result+=temp*temp;
n/=10;
}
if (result==1) {//如果result为1,则原正整数为happy number
return true;
}
if (path.find(result)!=path.end()) {//如果result已经在图中,即存在循环,所以key不是happy number
return false;
}
path[key]=result;//将key或result存储到图中
return isHappy(result);//递归计算
}
};

 当然解决方案还是有很多的,其中有很多是采用哈希表的递归方案:

class Solution {
public:
unordered_set<int> check;
bool isHappy(int n) {
string tmp = to_string(n);
int count = 0;
for(char each:tmp){
count += (each-48)*(each-48);
}
if(check.count(count) == 0)
check.insert(count);
else
return false;
return count == 1? true : isHappy(count);
}
};

其他解法:

运行时间:8ms
class Solution {
public:
bool isHappy(int n) {
map<int,int> temp;
while(true){
if(n==1)
return true;
if(temp[n]==1)
return false;
temp[n]++;
n = Caculate(n);
}
}
int Caculate(int n){
int ret=0;
while(n!=0){
ret+=(n%10)*(n%10);
n=n/10;
}
return ret;
}
};

 不过在本题中使用unordered_set还是要更好的,因为图中你的算法有插入和查找的时间。而且我们不是必须得存储计算结果(values),只需要知道是否看到过这个数字而已。

所以改进方案:

(运行时间:4ms)
class Solution {
public:
bool isHappy(int n) {
unordered_set<int> s;
while(true){
if(n==1)
return true;
if(s.find(n)!=s.end())
return false;
s.insert(n);
n = Caculate(n);
}
}
int Caculate(int n){
int ret=0;
while(n!=0){
ret+=(n%10)*(n%10);
n=n/10;
}
return ret;
}
};

  

  

leetcode:Happy Number的更多相关文章

  1. Leetcode:Largest Number详细题解

    题目 Given a list of non negative integers, arrange them such that they form the largest number. For e ...

  2. leetcode:Palindrome Number

    Question: Determine whether an integer is a palindrome. Do this without extra space. Some hints: Cou ...

  3. leetcode:Single Number

    public int SingleNumber(int[] nums) { if(nums==null||nums.Length%2==0) return 0; int ret=nums[0]; fo ...

  4. LeetCode之“排序”:Largest Number

    题目链接 题目要求: Given a list of non negative integers, arrange them such that they form the largest numbe ...

  5. [LeetCode] Super Ugly Number 超级丑陋数

    Write a program to find the nth super ugly number. Super ugly numbers are positive numbers whose all ...

  6. Leetcode 137 Single Number II 仅出现一次的数字

    原题地址https://leetcode.com/problems/single-number-ii/ 题目描述Given an array of integers, every element ap ...

  7. leetcode 136 Single Number, 260 Single Number III

    leetcode 136. Single Number Given an array of integers, every element appears twice except for one. ...

  8. LeetCode 137 Single Number II(仅仅出现一次的数字 II)(*)

    翻译 给定一个整型数组,除了某个元素外其余的均出现了三次. 找出这个元素. 备注: 你的算法应该是线性时间复杂度. 你能够不用额外的空间来实现它吗? 原文 Given an array of inte ...

  9. LeetCode:二叉搜索树中第K小的数【230】

    LeetCode:二叉搜索树中第K小的数[230] 题目描述 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素. 说明:你可以假设 k 总是有效的,1 ≤ k ...

随机推荐

  1. 运用socket实现简单的服务器客户端交互

    Socket解释: 网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket. Socket的英文原义是“孔”或“插座”.作为BSD UNIX的进程通信机制,取后一种意 ...

  2. shiro添加注解@RequiresPermissions不起作用

    这是因为没有开启spring拦截器,在spring-mvc.xml中加入以下代码就可以了(一定要写在最先加载的xml中,写在后面加载的xml中也不起作用) <bean class="o ...

  3. Centos编译安装PHP 5.5笔记

    本篇是在 Centos 6.4 32bit 下编译安装 php 5.5.5 的笔记,接上篇 Centos编译安装Apache 2.4.6笔记.php 5.5.x 和 centos 源里面的 php 5 ...

  4. .NET设计模式(3):抽象工厂模式(Abstract Factory)(转)

    概述 在软件系统中,经常面临着“一系列相互依赖的对象”的创建工作:同时由于需求的变化,往往存在着更多系列对象的创建工作.如何应对这种变化?如何绕过常规的对象的创建方法(new),提供一种“封装机制”来 ...

  5. SQLite中使用时的数据类型注意

    在使用SQLite时,要注意:在SQLite中的Integer类型,对应在C#中需要使用long类型或者Int64 在使用SQLite时,要注意:在SQLite中存放的日期类型必须是如此:yyyy-M ...

  6. ZOJ3560 Re:the Princess(高斯消元法)

    题目要读很久才能理解它的意思和笑点(如果你也看过那个笑话的话),读懂之后就会发现是一个高斯消元法的题目,对于我来说难点不在高斯消元,而在于字符串处理.先来说说题意吧: 总共有n个人,n个人都会有一段话 ...

  7. 2015年4月 非常干货之Python资源大全

    [非常干货之Python资源大全]Python是一门美妙的语言,简单易用,容易提升.它是一门主流语言,却没有其它专业语言的弊病,从游戏,ML,GUI到科学和数学有着巨量的函数库. 直击现场 <H ...

  8. C#调用脚本语言(三)-- IronJS 与 IronLua 简单方法性能比较

    1.   测试环境 1.1. 硬件环境 CPU:intel Core i7-740QM 内存:8GDDR3 Memory 1.2. 系统 系统:Windows 8 Enterprise 开发工具:Vs ...

  9. windows 两个用户,默认其中一个用户登录

    1. 在开始菜单中搜索“运行”,回车打开,或者Win+R打开运行窗口. 输入“control userpasswords2”或者“rundll32 netplwiz.dll,UsersRunDll”回 ...

  10. poj 3621(最优比率环)

    题目链接:http://poj.org/problem?id=3621 思路:之前做过最小比率生成树,也是属于0/1整数划分问题,这次碰到这道最优比率环,很是熟悉,可惜精度没控制好,要不就是wa,要不 ...