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

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

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

 

 

1.把数字各位放入数组,test(int n)方法.

2.计算各位之平方和,getsum(int[] arr)方法.

3.判断结束条件。

 

 

1 public class Solution { 2 public boolean isHappy(int n) { 3  4 int times=0; 5 int[] arr = test(n); 6  7 int sum = getsum(arr); 8  9 while(sum!=1){10 int[] ar = test(sum);11 sum = getsum(ar);12 times++;13 if(times>100){
//loop times,>100 loops endlessly in a cycle,it works.14 return false;15 }16 }17 System.out.println(sum);18 19 return true;20 }21 22 23 //get sum24 public int getsum(int[] arr){25 int sum = 0;26 for(int ii = 0;ii

 

 

392 ms.

转载于:https://www.cnblogs.com/catcoding/p/4707207.html

你可能感兴趣的文章
如何用javascript获取当前时间戳:
查看>>
PostGreSql安装
查看>>
idea maven 依赖报错 invalid classes root
查看>>
【剑指offer】合并两个排序的链表
查看>>
报到篇
查看>>
dubbo系列五、dubbo核心配置
查看>>
自定义ComboBox,简简单单实现
查看>>
MYSQL导入,导出命令。
查看>>
ORA-12560: TNS: 协议适配器错误
查看>>
Unsafe 学习和源码阅读
查看>>
YTU 2987: 调整表中元素顺序(线性表)
查看>>
JSP中文乱码
查看>>
Apache
查看>>
XE8 (RTM) Android SDK 更新安装
查看>>
ROS之rviz显示历史运动轨迹、路径的各种方法(visualization_msgs/Marker、nav_msgs/Path)...
查看>>
SCP-bzoj-1079
查看>>
Python 实践项目 游戏
查看>>
AJAX--Jquery
查看>>
模拟新浪微博随便看看
查看>>
环境搭建
查看>>