• [LeetCode202]Happy Number判断一个数是不是happy number


    题目:

    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则是happy number,否则不是)

    思路:同计算循环小数一样,把每次计算的结果保存到一个List<int>里,如果出现循环,则返回false即可

    代码:

    public class Solution {
        public bool IsHappy(int n) {
            int sum = n;
            if(n <= 0)
                return false;
            List<int> appearedNum = new List<int>();
            while(true)
            {
                if(appearedNum.Contains(sum))
                    return false;
                else
                    appearedNum.Add(sum);
                sum = GetNext(sum);
                if(sum == 1)
                    return true;
            }
            return true;
        }
        
        public int GetNext(int num)
        {
            int sum = 0;
    
            while(num != 0)
            {
                sum += (int)Math.Pow(num % 10, 2);
                num /= 10;
            }
            return sum;
        }
    }
  • 相关阅读:
    五子棋人机对战设计
    通过getSystemServices获取手机管理大全
    C#常见错误解决方法
    🍖数据增删改查页面搭建
    🍖django ORM 表关系与django 请求生命周期流程图
    🍖django ORM 简介
    🍖Python与django连接数据库
    🍖静态文件配置与request对象
    开启进程的两种方式
    进程PID 与PPID
  • 原文地址:https://www.cnblogs.com/zhangbaochong/p/5059755.html
Copyright © 2020-2023  润新知