Demo20快乐数

复制代码
/**
 * 编写一个算法来判断一个数 n 是不是快乐数。
 * 「快乐数」 定义为:
 * 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
 * 然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
 * 如果这个过程 结果为 1,那么这个数就是快乐数。
 * 如果 n 是 快乐数 就返回 true ;不是,则返回 false 。
 */
java 复制代码
public class Demo20 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个正整数");
        int n = sc.nextInt();
        if(n==1){
            System.out.println(n+"是快乐数");
        }
        Set<Integer> seen = new HashSet<>();
        while (!seen.contains(n)) {
            seen.add(n);
            n =getNext(n);
            if(n==1){
                System.out.println(n+"是快乐数");
                return;
            }
        }
        System.out.println(n+"不是快乐数");
    }


    public static int getNext(int n) {
        int totalSum = 0;

        while (n > 0) {
            totalSum += Math.pow(n % 10, 2);
            n /= 10;
        }

        return totalSum;
    }
}
相关推荐
小马爱打代码1 小时前
Spring Boot:模块化实战 - 保持清晰架构
java·spring boot·架构
Zsy_0510031 小时前
【数据结构】二叉树OJ
数据结构
小坏讲微服务1 小时前
SpringBoot4.0整合knife4j 在线文档完整使用
java·spring cloud·在线文档·knife4j·文档·接口文档·swagger-ui
8***Z891 小时前
springboot 异步操作
java·spring boot·mybatis
i***13242 小时前
Spring BOOT 启动参数
java·spring boot·后端
坚持不懈的大白2 小时前
后端:SpringMVC
java
IT_Octopus2 小时前
(旧)Spring Securit 实现JWT token认证(多平台登录&部分鉴权)
java·后端·spring
kk哥88992 小时前
Spring详解
java·后端·spring
S***26752 小时前
Spring Cloud Gateway 整合Spring Security
java·后端·spring
Tao____2 小时前
开源物联网平台
java·物联网·mqtt·开源·设备对接