LeetCode刷题之202-快乐数, happy number
「快乐数」 定义为:
- 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
- 然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
- 如果这个过程 结果为 1,那么这个数就是快乐数。
如果 n 是 快乐数 就返回 true ;不是,则返回 false 。
示例 1:
输入:n = 19 输出:true 解释: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
示例 2:
输入:n = 2 输出:false
提示:
1 <= n <= 231 - 1
执行用时:1 ms, 在所有 Java 提交中击败了81.56%的用户
内存消耗:38.5 MB, 在所有 Java 提交中击败了48.74%的用户
通过测试用例:404 / 404
1 class Solution { 2 public static int results[]=new int[810]; 3 public static int results_count=0; 4 5 public static boolean isHappy(int n) { 6 results_count=0; 7 do { 8 int digits[]=new int[10]; 9 int length_n=0; 10 11 for (int i=0; n>=1 ; i++) { 12 digits[i]= n % 10; 13 n=n/10; 14 length_n++; 15 } 16 17 int result=0; 18 for(int j=0; j<length_n; j++) { 19 result+=digits[j]*digits[j]; 20 } 21 22 if (result==1) 23 return true; 24 else{ 25 boolean insertOk = insertResults(result); 26 if (!insertOk) //have duplicate number in array 27 return false; 28 } 29 n = result; 30 } while(true); 31 } 32 //在结果数组中按从小到大插入新得的结果,如果数组中有重复,则返回false;如插入成功则返回true 33 public static boolean insertResults(int result) { 34 if(results_count==0) { 35 results[0]=result; 36 results_count++; 37 return true; 38 } 39 else { 40 int i=0; 41 for ( i=0; i<results_count; i++) { 42 if(result == results[i]) 43 return false; 44 if (result < results[i]) { 45 for(int j=results_count-1; j>=i; j--) 46 results[j+1] = results[j]; 47 results[i]=result; 48 results_count++; 49 return true; 50 } 51 } 52 results[i]=result; 53 results_count++; 54 } 55 return true; 56 } 57 }
- 换一个暴力破解算法,2 xxx xxx xxx -> 810- --> 240- --> 160- --> , 非happy number的最后序列必然是: 2-》4-》16-》37-》58--》89-->145-->42-->20--》4
执行结果:通过执行用时:1 ms, 在所有 Java 提交中击败了81.57%的用户内存消耗:38.3 MB, 在所有 Java 提交中击败了66.56%的用户通过测试用例:404 / 404
1 class Solution { 2 public boolean isHappy(int n) { 3 if(n==1) 4 return true; 5 6 // 2 xxx xxx xxx -> 810- --> 240- --> 160- --> 7 for(int i=0; i<100; i++) { 8 n=nextNum(n); 9 if(n==1) 10 return true; 11 } 12 return false; 13 } 14 //传入一个n,得到下一个n 15 int nextNum(int num) { 16 int result=0; 17 while(num>0) { 18 result+=(num%10)*(num%10); 19 num/=10; 20 } 21 return result; 22 } 23 }
浙公网安备 33010602011771号