博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Happy Number
阅读量:4073 次
发布时间:2019-05-25

本文共 1002 字,大约阅读时间需要 3 分钟。

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
Java代码:

public class Solution {    public boolean isHappy(int n) {        HashSet
set = new HashSet<>(); set.add(n); int tmp = 0; while (n > 0) { tmp += (n % 10) * (n % 10); n = n / 10; } if (tmp == 1) return true; int new_n = tmp; while (!set.contains(new_n) && tmp != 1) { set.add(new_n); tmp=0; while (new_n > 0) { tmp += (new_n % 10) * (new_n % 10); new_n = new_n / 10; } new_n =tmp; } if(tmp ==1) return true; else return false; }}
 

转载地址:http://svuni.baihongyu.com/

你可能感兴趣的文章
ubuntu 12.04 安装 GMA3650驱动
查看>>
新版本的linux如何生成xorg.conf
查看>>
xorg.conf的编写
查看>>
启用SELinux时遇到的问题
查看>>
virbr0 虚拟网卡卸载方法
查看>>
No devices detected. Fatal server error: no screens found
查看>>
新版本的linux如何生成xorg.conf
查看>>
virbr0 虚拟网卡卸载方法
查看>>
Centos 6.0_x86-64 终于成功安装官方显卡驱动
查看>>
Linux基础教程:CentOS卸载KDE桌面
查看>>
db sql montior
查看>>
read humor_campus
查看>>
IBM WebSphere Commerce Analyzer
查看>>
Unix + OS IBM Aix FTP / wu-ftp / proftp
查看>>
my read work
查看>>
db db2 base / instance database tablespace container
查看>>
hd disk / disk raid / disk io / iops / iostat / iowait / iotop / iometer
查看>>
project ASP.NET
查看>>
db db2_monitorTool IBM Rational Performace Tester
查看>>
OS + Unix Aix telnet
查看>>