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.叙事 我们在编码中,经常捣 ...
随机推荐
- android绘画折线图一
最近需要实现用android来画折线图,所以百度了一下,发现确实很多,也很乱,现在整理两种方法(第二种方法在[android绘画折线图二]中实现),仅供大家参考,一起学习研究. 第一种使用ChartF ...
- eclipse中tomcat加gc日志输出
-XX:ParallelGCThreads=4 -XX:+PrintGCDetails
- AngularJs初步学习笔记(part1)
一.摘要: angular是采用JavaScript编写的前端mvc框架,帮助开发者编写现代化的单页面应用.它尤其适用编写有大量CRUD操作的,具有Ajax风格的客户端应用. 二.总结: Angula ...
- WINRARA 排除 .svn 文件夹
加入-x*\.svn -x*\.svn\* 即可: rar.exe u -m3 -s -r -o+ -x*.db -x*.zip -x*.rar -x*\.svn -x*\.svn\* zmv9net ...
- 剑指offer系列37----数据流中的中位数
[题目]如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值, * 那么中位数就是所有数值排序之后位于中间的数值. package com.exe8.offer; import java.uti ...
- 【转】深入分析 iBATIS 框架之系统架构与映射原理
深入分析 iBATIS 框架之系统架构与映射原理 iBATIS 通过 SQL Map 将 Java 对象映射成 SQL 语句和将结果集再转化成 Java 对象,与其他 ORM 框架相比,既解决了 Ja ...
- C#语法杂谈
1. 值类型和引用类型 1.1 值类型 比如int,float,struct等,和C/C++中的变量差不多,但编译器会强制你必须先初始化再使用,避免一不小心使用了未初始化的变量. 1.2 引用类型 c ...
- maven本地仓库的配置以及如何修改默认.m2仓库位置
本地仓库是远程仓库的一个缓冲和子集,当你构建Maven项目的时候,首先会从本地仓库查找资源,如果没有,那么Maven会从远程仓库下载到你本地仓库.这样在你下次使用的时候就不需要从远程下载了.如果你所需 ...
- LDAP过滤器使用说明(用户、组和容器的默认 LDAP 过滤器和属性)
说明来源:http://docs.oracle.com/html/E35191_01/ldap-filters-attrs-users.html#ldap-filters-attributes-use ...
- [系统开发] Squid 认证系统
一.用途 用过 Squid 的用户认证模块的同事一定知道,它有个很麻烦的问题:每过一段时间就会跳出一个重新输入密码的窗口,用户不胜其烦,我查了网上的各种配置资料,始终没有找到一个圆满的解决方法,所以编 ...