[LeetCode] 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

解题思路

判断中间结果是否出现重复即可

实现代码[C++]

//Rumtime:10ms
class Solution {
public:
    bool isHappy(int n) {
        set<int> nums;
        while(true)
        {
            if (n == 1)
            {
                return true;
            }
            if (nums.find(n) == nums.end())
            {
                nums.insert(n);
                int sum = 0;
                while(n)
                {
                    int x = n % 10;
                    sum += x * x;
                    n /= 10;
                }
                n = sum;
            }
            else
            {
                return false;
            }
        }
    }
};

实现代码[Python]

# Runtime:76ms
class Solution:
    # @param {integer} n
    # @return {boolean}
    def isHappy(self, n):
        SQUARE = dict([(c, int(c)**2) for c in "0123456789"])
        s = set()
        while n != 1 and n not in s:
            s.add(n)
            n = sum(SQUARE[d] for d in str(n))
        return n == 1
时间: 2024-09-24 08:37:46

[LeetCode] Happy Number的相关文章

[LeetCode] Binary Number with Alternating Bits 有交替位的二进制数

Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Example 1: Input: 5 Output: True Explanation: The binary representation of 5 is: 101 Example 2: Input: 7 Output: False Ex

[LeetCode]191.Number of 1 Bits

题目 Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). For example, the 32-bit integer '11' has binary representation 00000000000000000000000000001011, so the function should r

[LeetCode]200.Number of Islands

题目 Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded

[LeetCode] Ugly Number II

Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. Note that 1 is typically treated as an

[LeetCode] Palindrome Number &amp;amp; Valid Palindrome - 回文系列问题

题目概述: Determine whether an integer is a palindrome. Do this without extra space. 题目分析: 判断数字是否是回文 例如121.656.3443 方法有很多,正着看和到着看两数相同:当然负数显然不是回文 我的方法: 第一种方法: 由于没有没有看到前面的without extra space.采用的方法是把数字转换为字符串,依次比较最前和最后两个字符是否相同,直到遍历完毕. /** * 判断一个数字是否是回文数字 Pal

[LeetCode] Single Number II

Given an array of integers, every element appears three times except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 解题思路 考虑全部用二进制表示,如果我们把 第 ith 个位置上所有数字的

[LeetCode] Single Number III

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. For example: Given nums = [1, 2, 1, 3, 2, 5], return [3, 5]. Note: The order

[LeetCode] Ugly Number

Write a program to check whether a given number is an ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. Note that 1 is ty

[LeetCode] Single Number

Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 解题思路 亦或运算. 实现代码 // Runtime: 1 ms public cla