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

Credits:
Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.

写一个算法判断一个数是不是快乐数。快乐数:一个正整数,如果对其各个位上的数字分别平方求和得到一个新的数,再进行同样的操作,如果结果变成了1,则说明是快乐数。

解法:循环求平方和,即求出当前数组的平方和后,再以此平方和作为新的数继续求平方和,而循环终止条件是:得到的平方和为1,或得到的平方和在之前的循环中出现过,那以后会一直循环,不可能达到1。判断平方和是否为1很简单,每次检查就好了;而判断平方和是否出现过,则只需要维持一个Set,每次循环检查当前平方和是否在Set中,在则终止循环,不在则将此平方和放到Set中。

Java:

public class Solution {
public boolean isHappy(int n) {
Set<Integer> got = new HashSet<>();
while (n != 1 && !got.contains(n)) {
got.add(n);
int sum = 0;
while (n != 0) {
sum += Math.pow(n % 10, 2);
n /= 10;
}
n = sum;
}
return n == 1;
}
}

Python:

class Solution:
# @param {integer} n
# @return {boolean}
def isHappy(self, n):
lookup = {}
while n != 1 and n not in lookup:
lookup[n] = True
n = self.nextNumber(n)
return n == 1 def nextNumber(self, n):
new = 0
for char in str(n):
new += int(char)**2
return new  

Python:

class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
got = set()
while n != 1 and n not in got:
got.add(n)
sum = 0
while n:
sum += (n % 10)**2
n //= 10
n = sum return n == 1

C++:

class Solution {
public:
bool isHappy(int n) {
set<int> got;
while (n != 1 && got.find(n) == got.end()) {
got.insert(n);
int sum = 0;
while (n) {
sum += pow(n % 10, 2);
n /= 10;
}
n = sum;
}
return n == 1;
}
};

  

All LeetCode Questions List 题目汇总

[LeetCode] 202. Happy Number 快乐数的更多相关文章

  1. 202 Happy Number 快乐数

    写一个算法来判断一个数是不是“快乐数”.一个数是不是快乐是这么定义的:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,或是无限循环但始终变不到 1.如 ...

  2. Leetcode 202 Happy Number 弗洛伊德判环解循环

    今天先谈下弗洛伊德判环,弗洛伊德判环原来是在一个圈内有两人跑步,同时起跑,一人的速度是另一人的两倍,则那个人能在下一圈追上另一个人,弗洛伊德判环能解数字会循环出现的题,比如说判断一个链表是不是循环链表 ...

  3. [LeetCode] Happy Number 快乐数

    Write an algorithm to determine if a number is "happy". A happy number is a number defined ...

  4. [LeetCode] 136. Single Number 单独数

    Given a non-empty array of integers, every element appears twice except for one. Find that single on ...

  5. [LeetCode] 246. Strobogrammatic Number 对称数

    A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside ...

  6. LeetCode 202. Happy Number (快乐数字)

    Write an algorithm to determine if a number is "happy". A happy number is a number defined ...

  7. [LeetCode] 263. Ugly Number 丑陋数

    Write a program to check whether a given number is an ugly number. Ugly numbers are positive numbers ...

  8. LeetCode 202 Happy Number

    Problem: Write an algorithm to determine if a number is "happy". A happy number is a numbe ...

  9. [LintCode] Happy Number 快乐数

    Write an algorithm to determine if a number is happy. A happy number is a number defined by the foll ...

随机推荐

  1. 微信小程序~下拉刷新PullDownRefresh

      一.onPullDownRefresh回调 代码: // http://itlao5.com onPullDownRefresh: function () { console.log('onPul ...

  2. 《exception》第九次团队作业:Beta冲刺与验收准备(大结局)

    一.项目基本介绍 项目 内容 这个作业属于哪个课程 任课教师博客主页链接 这个作业的要求在哪里 作业链接地址 团队名称 Exception 作业学习目标 1.掌握软件黑盒测试技术:2.学会编制软件项目 ...

  3. 《CoderXiaoban》第八次团队作业:Alpha冲刺

    项目 内容 这个作业属于哪个课程 任课教师博客主页链接 这个作业的要求在哪里 实验十二 团队作业8:软件测试与ALPHA冲刺 团队名称 Coderxiaoban团队 作业学习目标 (1)掌握软件测试基 ...

  4. Cocos2d-x学习小结 配置篇

    Cocos2d-x学习小结 配置篇 学习工具:Cocos2d-x用户手册,<Cocos2d-x游戏开发之旅> 首先官网下载cocos2d-x源码,安装vs2019.如果没有安装python ...

  5. Task 使用方法

    Task的使用方法 1. 调用无参数.无返回值方法 private void button1_Click(object sender, EventArgs e) { Task task = new T ...

  6. JavaScript基础07——BOM

    BOM概念   BOM是Browser Object Model的缩写,简称浏览器对象模型.这个对象就是window         BOM提供了独立于内容而与浏览器窗口进行交互的对象         ...

  7. HTML 009 select_jquery操作下拉框select

    取值问题 <select id="selector"> <option value="1">选项一</option> < ...

  8. js 键盘事件(onkeydown、onkeyup、onkeypress)

    onkeypress 这个事件在用户按下并放开任何字母数字键时发生.系统按钮(例如,箭头键和功能键)无法得到识别. onkeyup 这个事件在用户放开任何先前按下的键盘键时发生. onkeydown ...

  9. hibernate实现增删改查

    1.需要先创建学生实体: package pers.zhb.domain; public class Student { private int studentno; private String s ...

  10. mybatis-generator 插件

    首先肯定要有mybatis的依赖 <!--mybatis spring--> <dependency> <groupId>org.mybatis.spring.bo ...