资讯专栏INFORMATION COLUMN

[LeetCode/LintCode] Happy Number

崔晓明 / 1837人阅读

Problem

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^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

Solution updated 2018-9
class Solution {
    public boolean isHappy(int n) {
        Set record = new HashSet<>();
        while (n != 1) {
            if (record.contains(n)) return false;
            record.add(n);
            int sum = 0;
            while (n != 0) {
                //calculate sum
                sum += Math.pow(n%10, 2);
                n /= 10;
            }
            n = sum;
        }
        return true;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65413.html

相关文章

  • [LeetCode/LintCode] Number of Islands [DFS]

    摘要:两个循环遍历整个矩阵,出现则将其周围相邻的全部标记为,用子函数递归标记。注意里每次递归都要判断边界。写一个的,写熟练。 Number of Islands Problem Given a boolean/char 2D matrix, find the number of islands. 0 is represented as the sea, 1 is represented as...

    Fourierr 评论0 收藏0
  • [LeetCode/LintCode] Plus One

    Problem Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list. Example Given [1,2...

    sunsmell 评论0 收藏0
  • [LeetCode/LintCode] Top K Frequent Words

    LeetCode version Problem Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, t...

    0x584a 评论0 收藏0
  • [LeetCode/LintCode] Odd Even Linked List

    Problem Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. Example Example:Given...

    awokezhou 评论0 收藏0
  • [LeetCode/LintCode] Largest Palindrome Product

    Problem Find the largest palindrome made from the product of two n-digit numbers. Since the result could be very large, you should return the largest palindrome mod 1337. Example Input: 2Output: 987Ex...

    Barry_Ng 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<