力扣简202 快乐数
作者:互联网
自己手写:
package leetcode01; /*编写一个算法来判断一个数 n是不是快乐数。 「快乐数」定义为: 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。 然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。 如果这个过程结果为1,那么这个数就是快乐数。 如果 n是快乐数就返回 true;不是,则返回 false.*/ public class Solution202 { public static int square(int n) { int res=0; int mul=n; int rem=0; while(mul!=0) { rem=mul%10; res=res+rem*rem; mul=mul/10; } return res; } public static boolean isHappy(int n) { int max=0; while(n!=1) { n=square(n); max++; if(max>=1000) { break; } } if(n==1) return true; return false; } public static void main(String[] args) { // TODO Auto-generated method stub System.out.print(isHappy(19)); } }
标签:202,int,res,力扣,快乐,rem,mul,public 来源: https://www.cnblogs.com/ayuanjiejie/p/16324646.html