Algorithm questions daily practice---Day 74: Happy Numbers

Get into the habit of writing together! This is the 9th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

1. Problem description

Write an algorithm to determine if a number  n is a happy number.

The "Happy Number"  is defined as:

  • For a positive integer, each time the number is replaced by the sum of the squares of the digits in each of its positions.
  • Then repeat this process until the number becomes 1, or it may be  an infinite loop  but it never becomes 1.
  • If the  result of this process is  1, then the number is a happy number.

 Return  if it  n is a  happy numbertrue  ; if not, return it  false .

Topic link: Happy Numbers .

Second, the subject requirements

Sample

输入: n = 19
输出: true
解释: 12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
复制代码

visit

1.数学思想
2.建议用时15~35min
复制代码

3. Problem Analysis

Happy numbers are easy to understand, just divide the digits and add them squared. Here we need an ending condition, that is, it must be 2 digits.

When n belongs to 1~9, exit the loop of adding digits. And the last unit number is only 1 or 7 to end the cycle and become a happy number.

Such as the cycle process of 7: 7 2 = 49 = 4 2 + 9 2 = 97 = 9 2 + 7 2 = 130 = 1 2 + 3 2 + 0 = 10 = 1 7^2=49=4^2+9^2=97=9^2+7^2=130=1^2+3^2+0=10=1

Other numbers, temporarily becoming unhappy numbers, will enter a 4 16 37 58 89 145 42 20 4 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 , the cycle repeats.

3.gif

Fourth, the encoding implementation

class Solution {
public:
    bool isHappy(int n) {
        int k,ans;//初始化定义
        while(n>9)//单位数字直接退出
        {
            k=n;//暂存
            ans=0;//存储位数平方相加的结果
            while(k)
            {
                ans+=(k%10)*(k%10);//平方相加
                k=k/10;
            }
            n=ans;
        }
        if(n==1||n==7)//1或7,输出true
            return true;
        else
            return false;
    }
};
复制代码

5. Test results

2.png

1.png

Guess you like

Origin juejin.im/post/7084389996483837965