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
1^2 + 9^2 = 828^2 + 2^2 = 686^2 + 8^2 = 1001^2 + 0^2 + 0^2 = 1s思路: 1. 就是檢測(cè)是否有l(wèi)oop,如果出現(xiàn)loop還沒(méi)有發(fā)現(xiàn)1,那就是沒(méi)1,就不是happy number 2. loop就看是否出現(xiàn)兩次,檢查重復(fù),就用hash做! 3. 網(wǎng)上發(fā)現(xiàn)另一種,利用快慢指針的方法做,可以省掉hash的空間,這個(gè)方法就是在鏈表中多次使用的用于檢測(cè)cycle的方法。 4. 用一快一慢兩個(gè)指針,當(dāng)快指針和慢指針相遇,說(shuō)明遇到環(huán)了,如果在此之前還沒(méi)發(fā)現(xiàn)快指針指向1,則這個(gè)環(huán)沒(méi)有1,因此就不是happy number 5. 把鏈表中的方法運(yùn)用在這個(gè)場(chǎng)合,說(shuō)明第一個(gè)想到這個(gè)方法的人,是打破了思維中的限制:認(rèn)為快慢指針只能用在鏈表中來(lái)找cycle。只有思維里沒(méi)有這個(gè)限制或者打破了這層限制,才能看到這個(gè)方法起始有更廣的應(yīng)用范圍,除了鏈表,一切前后相繼的數(shù),或者找任何地方的cycle,都可以認(rèn)準(zhǔn)快慢指針大法! 6. 在方法2中,用到do-while,而不用while。平時(shí)寫代碼幾乎不用do while。這里為啥非要用do-while呢?后面代碼2.1嘗試用while來(lái)替代do-while,很麻煩。原因是:do-while可以先計(jì)算,后判斷;而while上來(lái)就先判斷,然后才計(jì)算。而這道題,slow和fast初值都是n,而判斷是否跳出循環(huán)的條件是slow!=fast,現(xiàn)在用while就不行,因?yàn)閟low和fast初始值相等,所以無(wú)法進(jìn)入while。因此,就應(yīng)該用do-while,來(lái)做到初始值相等,但運(yùn)算之后不等的情況!
//方法1:hash找cycleclass Solution {public: bool isHappy(int n) { // unordered_set<int> ss; while(n!=1){ if(ss.count(n)) return false; ss.insert(n); int cur=0; while(n){ cur+=((n%10)*(n%10));//bug:+=這種簡(jiǎn)寫容易出現(xiàn)的bug,后面一定要優(yōu)先計(jì)算,因此必須用括號(hào)提高優(yōu)先級(jí) n/=10; } n=cur; } return true; }};//方法2:快慢指針找cycle!class Solution {public: int happy(int n){ int res=0; while(n){ res+=((n%10)*(n%10)); n/=10; } return res; } bool isHappy(int n) { // int slow=n,fast=n; do{//思考一下為什么用do-while?不能用while slow=happy(slow); fast=happy(happy(fast)); if(fast==1) return true; }while(slow!=fast); return false; }};//方法2.1:快慢指針找cycle!嘗試把do-while換成while,費(fèi)勁!還是do-while好用!class Solution {public: int happy(int n){ int res=0; while(n){ res+=((n%10)*(n%10)); n/=10; } return res; } bool isHappy(int n) { // int slow=n,fast=happy(n); while(slow!=fast){ slow=happy(slow); fast=happy(happy(fast)); if(fast==1) return true; } return fast==1; }};
|
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注