0
点赞
收藏
分享

微信扫一扫

论文阅读》通过混合潜在变量实现多样化、相关和连贯的开放领域对话生成 AAAI 2023

龙毓七七 2024-05-28 阅读 6
算法

题目

在这里插入图片描述
题目链接:
https://www.nowcoder.com/practice/293b9ddd48444fa493dd17da0feb192d

思路

	  直接模拟即可

Java代码

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param n int整型
     * @return bool布尔型
     */
    public boolean happynum (int n) {
        //直接模拟即可
        if (n == 1) return true;
        Set<Integer> visited = new HashSet<>();

        while (!visited.contains(n)) {
            int next = 0;
            visited.add(n);
            while (n > 0) { //获得n每一位上的数字,并平方累加
                int cur = n % 10;
                next += cur * cur;
                n = n / 10;
            }
            if (next == 1) return true;
            if (visited.contains(next)) {
                return false;
            }

            n = next;
        }


        return false;
    }
}

Go代码

package main

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param n int整型
 * @return bool布尔型
 */
func happynum(n int) bool {
	//直接模拟即可
	if n == 1 {
		return true
	}

	set := map[int]bool{}

	_, ok := set[n]
	for !ok {
		set[n] = true
		next := 0

		for n > 0 { //获得n上的每一位数并累加
			cur := n % 10
			next += cur * cur
			n = n / 10
		}

		if next == 1 {
			return true
		}

		_, ok1 := set[next]
		if ok1 {
			return false
		}

		n = next
	}

	return false
}

PHP代码

<?php


/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param n int整型 
 * @return bool布尔型
 */
function happynum( $n )
{
     //直接模拟即可
    if($n ==1) return true;
    $set = [];

    while (true){
        $set[$n] = 1;

        $next = 0;

        while ($n>0){ //获取n上每一位数并累加
            $cur = $n%10;
            $next+=$cur*$cur;
            $n = intval($n/10);
        }

        if($next ==1) return true;
        if(isset($set[$next])) break;
        $n = $next;
    }


    return false;
}
举报

相关推荐

0 条评论