LeetCode之Happy Number

举报
chenyu 发表于 2021/07/26 23:24:15 2021/07/26
【摘要】 1、题目   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...

1、题目

 

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

Credits:
Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.

Subscribe to see which companies asked this question.

 

 

 

2、分析

这个题目每次会把每位的平方相加,然后循环这样,然后知道这个数字等于1为止,经过我们举例分析,如果不是快乐数最终或者中途出现这些数字,最後都会进入 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 的循环中

 

 

3、代码实现

 


  
  1. public class Solution {
  2. public boolean isHappy(int n) {
  3. if (n <= 0)
  4. return false;
  5. int result = 0;
  6. while (n != 0) {
  7. int temp = n % 10;
  8. result += temp * temp;
  9. n = n / 10;
  10. }
  11. if (result == 1)
  12. return true;
  13. else if (result == 4 || result == 16 || result == 37 || result == 58 || result == 89 || result == 145 || result == 42 || result == 20 )
  14. return false;
  15. else
  16. return isHappy(result);
  17. }
  18. }

 

 

 

 

 

 

 

文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。

原文链接:chenyu.blog.csdn.net/article/details/69788173

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。