HappyNum
/*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*/
import java.util.*; public class HappyNum { public static void main(String[] args) {
// TODO Auto-generated method stub System.out.println(isHappy(19)); } /**
* @param n
*/ public static int pingfanghe(int n) {
int sum = 0;
while (n != 0) {
sum += (n % 10) * (n % 10);
n = n / 10;
}
return sum;
} public static boolean isHappy(int n) {
/*
* int sum=0; char[] ch=String.valueOf(n).toCharArray(); for(int
* i=0;i<ch.length;i++) sum+=(ch[i])*ch[i]; //这样不行,返回的是asc码
* System.out.println(sum); if(n==1) return true; else return
* isHappy(n);
*/
/*
* if(n==1) return true; Set<Integer> al=new HashSet<Integer>(); int
* sum=0; while(n!=0) { al.add(n%10); n=n/10; } System.out.println(al);
* for(int i=0;i<al.size();i++) sum+=al.*al.get(i); n=sum;
* System.out.println(n);
*
*
*
* // return isHappy(n);
*
* return isHappy(n);
*/ Set<Integer> hs = new HashSet<Integer>();
while (true) {
if (hs.contains(n))
return false;
if (n == 1)
return true;
hs.add(n);
n = pingfanghe(n); } } }
注意:1.循环的判断
2.字符数组转化是不行的,输出的是asc码。
3.集合框架的使用
HappyNum的更多相关文章
- C# 通俗说 委托(和事件)
1.闲聊 编码一两年, 我走过了字段, 我跑过了类, 却翻不过方法.(不能灵活使用方法吧) (写这篇博客全程听将夜中<永夜>歌曲写完的,一气呵成,安利一下) 2.叙事 我们在编码中,经常捣 ...
随机推荐
- Mysql 索引 转载
转自 :http://blog.csdn.net/wud_jiyanhui/article/details/7403375 什么是索引 索引时一种特殊的文件,他们包涵着对数据表里所有记录的引用指针. ...
- AndroidStudio 应用(一)
1.下载安装,用上vpn了都: 2.配置模拟器,出现问题:VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_V ...
- C#获取相对路径
C#最常使用的相对路径是从当前程序所在路径开始相对寻径,找到要找的路径,即以下两种最简单的方式: 1. 程序根目录.(即exe程序所在路径) //下面两个路径是等价的,都是exe程序所在路径(通常是b ...
- Android 服务端开发之开发环境配置
Android 服务端开发之开发环境配置 这里是在Eclipse的基础上安装PhpEclipse插件方法,PHPEclipse是Eclipse的 一个用于开发PHP的插件.当然也可以采用Java开发a ...
- C/C++中产生随机数(rand,srand用法)
计算机的随机数都是由伪随机数,即是由小M多项式序列生成的,其中产生每个小序列都有一个初始值,即随机种子.(注意: 小M多项式序列的周期是65535,即每次利用一个随机种子生成的随机数的周期是65535 ...
- HTML5外包团队——技术分享:HTML5判断设备在线离线及监听网络状态变化例子
<!doctype html> <html> <head> <meta http-equiv="content-type" content ...
- 理解Javascript参数中的arguments对象
ECMAScript中函数没有标签名的特性,所以ECMAScript函数中没有重载. Javascript中arguments的存在可以弥补javascript中函数没有重载的不足. Javascri ...
- Puppet's Architecture 3.7
Puppet configures systems in two main stages: Compile a catalog Apply the catalog The Agent/Master A ...
- RabbitMQ和Kafka
转自通九大神的博客 起因 最近公司RabbitMQ的集群出了点问题,然后有些亲就说RabbitMQ慢且不好用,是一个瓶颈,不如换成Kafka.而我本人,使用RabbitMQ有一点久了,认为这个事情应当 ...
- ifconfig报错:SIOCSIFFLAGS: Operation not permitted
# insmod mt7601Usta.ko rtusb init rt2870 --->usbcore: registered new interface driver rt2870 # iw ...