zoukankan      html  css  js  c++  java
  • [LeetCode] Happy Number

    Well, no matter whether the number is happy or not, its sum-of-squared-digits sequance has a cycle. Well, do you still remember the algorithm for detecting cycles in linked lists? Yeah, use a fast and a slow pointer. That's also applicable to this problem.

    The code is as follows (idea from here).

     1 class Solution {
     2 public:
     3     bool isHappy(int n) {
     4         int slow = n, fast = n;
     5         do {
     6             slow = squareDigits(slow);
     7             fast = squareDigits(squareDigits(fast));
     8         } while (slow != fast);
     9         return fast == 1;
    10     }
    11 private:
    12     int squareDigits(int n) {
    13         int sq = 0;
    14         while (n) {
    15             sq += (n % 10) * (n % 10);
    16             n /= 10;
    17         }
    18         return sq;
    19     }
    20 };
  • 相关阅读:
    稀疏核机
    核方法
    变分法
    拉格朗日乘子
    序列数据
    连续隐含变量
    线性回归模型
    采样方法
    线性分类模型
    一些音乐下的评论
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4735358.html
Copyright © 2011-2022 走看看