202. Happy Number(LeetCode)

【202. Happy Number(LeetCode)】智慧并不产生于学历,而是来自对于知识的终生不懈的追求。这篇文章主要讲述202. Happy Number(LeetCode)相关的知识,希望能为你提供帮助。
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 class Solution { 2 public: 3int fang(int n) 4{ 5int sum = 0; 6while (n != 0) 7{ 8sum += (n % 10)*(n % 10); 9n = n / 10; 10} 11cout< < sum< < endl; 12return sum; 13} 14 15bool isHappy(int n) { 16int i=0; 17while (n!=1& & i< 100) 18{ 19n = fang(n); 20cout< < n< < endl; 21i++; 22} 23if (n == 1& & i< 100) 24{ 25return true; 26} 27if (i > = 100) 28return false; 29} 30 };

    1 class Solution { 2 public: 3bool isHappy(int n) { 4unordered_map< int, bool> m; 5while (n != 1 & & !m.count(n)){ 6m[n] = true; 7int new_n = 0; 8while (n){ 9new_n += (n % 10)*(n % 10); 10n /= 10; 11} 12n = new_n; 13} 14return n == 1; 15} 16 };

     

    推荐阅读