NC391. 快乐数
描述
示例1
输入:
19
输出:
true
示例2
输入:
111
输出:
false
C++ 解法, 执行用时: 3ms, 内存消耗: 396KB, 提交时间: 2022-07-24
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return bool布尔型 */ bool happynum(int n) { unordered_set<int>set; while(1) { n=summary(n); if(n==1) return true; if(set.find(n)!=set.end()) return false; else set.insert(n); } } int summary(int n) { int sum=0; while(n) { sum+=pow(n%10,2); n=n/10; } return sum; } };
C 解法, 执行用时: 3ms, 内存消耗: 396KB, 提交时间: 2022-04-14
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return bool布尔型 * * C语言声明定义全局变量请加上static,防止重复定义 */ #include<stdbool.h> int change(int x){ int sum = 0; while( x > 0){ int j = x % 10; sum = sum + j*j; x = x / 10; } return sum; } bool happynum(int n ) { while(n > 9){ n = change(n); } if(n == 1) return true; else return false; }
C++ 解法, 执行用时: 3ms, 内存消耗: 404KB, 提交时间: 2022-04-02
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return bool布尔型 */ int func(int c) { int sum = 0; while(c) { int temp = c %10; c /= 10; sum += temp * temp; } return sum; } bool happynum(int n) { // write code here int c = n; while(n>9) { n = func(n); } return n==1; } };
C++ 解法, 执行用时: 3ms, 内存消耗: 404KB, 提交时间: 2022-03-24
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return bool布尔型 */ int Ispf(int x) { int res = 0,d; while(x) { d=x%10; res+=d*d; x/=10; } return res; } bool happynum(int n) { // write code here //快慢指针 int fast = n,slow = n; do{ slow = Ispf(slow); fast = Ispf(Ispf(fast)); }while(slow!=fast); return slow==1; } };
C++ 解法, 执行用时: 3ms, 内存消耗: 412KB, 提交时间: 2022-03-23
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return bool布尔型 */ int sum( int num){ int res=0; while(num!=0){ res=res+(num%10)*(num%10); num=num/10; } return res; } bool happynum(int n) { // write code here unordered_set<int>uset; while(n!=1){ uset.insert(n); n=sum(n); if(uset.find(n)!=uset.end())return false; } return true; } };