leetCode 202. Happy Number 哈希

简介:

202. Happy Number

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

思路:

采用set来判断容器中是否有该元素出现过,如果出现过,那么就形成了环状,结果返回false。否则找到快乐数字。返回true。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class  Solution {
public :
     bool  isHappy( int  n) {
         set< int  > myset;
         int  total = 0;
         while (n != 1)
         {
             while (n)
             {
                 total += (n%10)*(n%10);
                 n /= 10;
             }
             if (total == 1)
                 return  true ;
             if (myset.find(total) != myset.end())
                 return  false ;
             else
                 myset.insert(total);
             n = total;
             total = 0;
         }
         return  true ;
     }
};

关于set容器的使用练习。


本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1837555

相关文章
|
2月前
《LeetCode》—— 哈希
《LeetCode》—— 哈希
|
2月前
leetcode-1044:最长重复子串(滚动哈希)
leetcode-1044:最长重复子串(滚动哈希)
40 0
|
8月前
|
算法
Leetcode 313. Super Ugly Number
题目翻译成中文是『超级丑数』,啥叫丑数?丑数就是素因子只有2,3,5的数,7 14 21不是丑数,因为他们都有7这个素数。 这里的超级丑数只是对丑数的一个扩展,超级丑数的素因子不再仅限于2 3 5,而是由题目给定一个素数数组。与朴素丑数算法相比,只是将素因子变了而已,解法还是和朴素丑数一致的。
73 1
|
21天前
|
存储 SQL 算法
LeetCode 题目 65:有效数字(Valid Number)【python】
LeetCode 题目 65:有效数字(Valid Number)【python】
|
21天前
|
算法 数据挖掘 开发者
LeetCode题目55:跳跃游戏【python5种算法贪心/回溯/动态规划/优化贪心/索引哈希映射 详解】
LeetCode题目55:跳跃游戏【python5种算法贪心/回溯/动态规划/优化贪心/索引哈希映射 详解】
|
20天前
|
存储 SQL 算法
LeetCode 题目 87:递归\动态规划\哈希实现 扰乱字符串
LeetCode 题目 87:递归\动态规划\哈希实现 扰乱字符串
|
2月前
[leetcode] 705. 设计哈希集合
[leetcode] 705. 设计哈希集合
|
2月前
|
存储 算法
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
16 0
|
2月前
leetcode-1001:网格照明(自定义哈希集合)
leetcode-1001:网格照明(自定义哈希集合)
24 0
|
8月前
|
存储
Leetcode Single Number II (面试题推荐)
给你一个整数数组,每个元素出现了三次,但只有一个元素出现了一次,让你找出这个数,要求线性的时间复杂度,不使用额外空间。
25 0