Leetcode算法学习日志-202 Happy Number

Leetcode 202 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(得到1后再进行平方和操作值不再变化)就为快乐数,不然就返回false。

解法分析

对于任何a0000形式的数,经过平方和后的数一定小于他本身,因此对于n>100的数,平方和g(n)

class Solution {
public:
    int squareSum(int n){
        int res=0;
        while(n){//this is important
            res+=(int)pow(double(n%10),2);
            n/=10;
            cout<



你可能感兴趣的:(算法,leetcode,双指针,C++,leetcode,算法,双指针)