LeetCode每日一题: 快乐数(No.202)

栏目: 编程工具 · 发布时间: 7年前

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

示例:

输入: 19
输出: true
解释: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
复制代码

思考:

用一个map来存放存放每次平方和计算完成的结果,一旦出现重复就说明这个数会陷入循环,就break返回false。
不重复就一直求各个位平方和,直至结果为1结束循环返回true。
复制代码

实现:

class Solution {
    public boolean isHappy(int n) {
        Map<Integer, Integer> map = new HashMap<>();
        boolean flag = true;
        while (n != 1) {
            int temp = n;
            n = 0;
            while (temp > 0) {
                n += Math.pow(temp % 10, 2);
                temp /= 10;
            }
            if (map.get(n) == null) {
                map.put(n, n);
            } else {
                flag = false;
                break;
            }
        }
        return flag;
    }
}复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Introduction to Programming in Java

Introduction to Programming in Java

Robert Sedgewick、Kevin Wayne / Addison-Wesley / 2007-7-27 / USD 89.00

By emphasizing the application of computer programming not only in success stories in the software industry but also in familiar scenarios in physical and biological science, engineering, and appli......一起来看看 《Introduction to Programming in Java》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具