快乐数
題目描述
編寫一個算法來判斷一個數是不是“快樂數”。
一個“快樂數”定義為:對于一個正整數,每一次將該數替換為它每個位置上的數字的平方和,然后重復這個過程直到這個數變為 1,也可能是無限循環但始終變不到 1。如果可以變為 1,那么這個數就是快樂數。
示例:
輸入: 19 輸出: true 解釋: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1題目解法
解法1
通過使用Set去重,判斷是否出現了循環
public boolean isHappy(int n) {if(n<1) {return false;}int count=0, wei=0;Set<Integer> set = new HashSet<Integer>();while(true) {count=0;while(n>0) {wei = n%10;count+=(wei*wei);n/=10;}if(count==1) {return true;}else if (set.contains(count)) {return false;}set.add(count);n = count;}}解法2
解法1的優化版,不使用額外存儲,使用快慢指針
public boolean isHappy(int n) {if(n<1) {return false;}int fast=n,slow=n;while(true) {slow = getCount(slow);fast = getCount(getCount(fast));if(slow==1 || fast==1) {return true;}else if (fast == slow) {return false;}}}private int getCount(int n) {int count=0, wei=0;while(n>0) {wei = n%10;count+=(wei*wei);n/=10;}return count;}解法3
解法3,利用數學規律,10以內的數字,只有1和7是快樂數,其他都不是。
public boolean isHappy(int n) {if(n<1) {return false;}int count=0, wei=0;while(true) {count=0;while(n>0) {wei = n%10;count+=(wei*wei);n/=10;}if(count==1 || count==7) {return true;}if (count < 10) {return false;}n=count;}}總結
- 上一篇: 怎样在百度定位自己公司位置 学会这招轻松
- 下一篇: 同构字符串