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. python+正则提取+ip代理爬取糗事百科文字信息

    很多网站都有反爬措施,最常见的就是封ip,请求次数过多服务器会拒绝连接,如图: 在程序中设置一个代理ip,可有效的解决这种问题,代码如下: # 需要的库 import requests import ...

  2. 深度学习Keras框架笔记之核心层基类

    Keras的Layers,就是构成网络的每一层.Keras实现了很多层,包括核心层.卷基层.RNN网络层等诸多常用的网络结构.下面开介绍核心层中包含了哪些内容.因为这个核心层我现在还没有全部用到,所以 ...

  3. 【转】RabbitMQ 关键词

    [转]RabbitMQ 关键词 RabbitMQ是流行的开源消息队列系统,用erlang语言开发.RabbitMQ是AMQP(高级消息队列协议)的标准实现. RabbitMQ中间件分为服务端(Rabb ...

  4. .net解决大文件断点续传

    以ASP.NET Core WebAPI 作后端 API ,用 Vue 构建前端页面,用 Axios 从前端访问后端 API ,包括文件的上传和下载. 准备文件上传的API #region 文件上传  ...

  5. pgloader 学习(六) 加载csv 数据

    关于加载的配置参数都是使用comand file command file 参考格式 LOAD CSV FROM 'GeoLiteCity-Blocks.csv' WITH ENCODING iso- ...

  6. 使用jstack命令查看CPU高占用的问题记录

    笔记: 1.top命令找出最高占用的进程(command为java) 2.查看高负载进程下的高负载线程:top -Hp [PID] (或 ps -mp PID -o THREAD,tid,time) ...

  7. 守护进程daemon.c

    它的特点是:•不占用控制终端(后台运行)•独立于控制终端•周期性运行 #include<stdio.h>#include<unistd.h>#include<fcntl. ...

  8. 3D数据采集和重建

    3D数据采集和重建是从传感器数据生成三维或时空模型.一般而言,这些技术和理论适用于大多数或所有传感器类型,包括光学,声学,激光扫描,[1]雷达,热学,[2]地震.[3][4] 内容 ·        ...

  9. 微信小程序 按钮固定在页面底部遮住页面显示内容问题

    我们分为以下部分来解决这个问题: 第一部分:问题的表现是怎么样的? 第二部分:问题的是如何实现的? 第三部分:如何解决问题? 第一部分:问题的表现是怎么样的? 我设置了页面有0-99共100个数,但是 ...

  10. 高斯混合模型(GMM)及MATLAB代码

    之前在学习中遇到高斯混合模型,卡了很长一段时间,在这里记下学习中的一些问题以及解决的方法.希望看到这篇文章的同学们对高斯混合模型能有一些基本的概念.全文不废话,直接上重点. 本文将从以下三个问题详解高 ...