1. 程式人生 > 其它 >leetcode202_快樂數

leetcode202_快樂數

1、題目描述

2、分析

 我本來是想著,如果是迴圈的話,就直接設定一個數字判斷這種情況但是其實並沒有將迴圈給判斷出來。

總的思路來說,就利用陣列計算一次,該數字所有位置上的數目平方和。

如果等於1則完成驗算,如果運算次數超過三百則也停止,返回False。

程式碼如下:

class Solution {
public:
    bool isHappy(int n) {
        int count=0;
        vector<int> num;
        while(n!=1){
            //num清零
            vector<int
>().swap(num); while(n!=0){ int num_digit = n%10; n = n/10; num.push_back(num_digit); } //求解平方和 for(auto i : num){ n = n + i*i; } count++; if(count>=100)
return false; } return true; } };

3、例子

別人的想法很好,其實也是跟以前的例子類似,主要就是利用快慢指標判斷迴圈。

參考方法:分析

程式碼:

class Solution {
public:
    int bitSquareSum(int n) {
        int sum = 0;
        while(n > 0)
        {
            int bit = n % 10;
            sum += bit * bit;
            n = n / 10
; } return sum; } bool isHappy(int n) { int slow = n, fast = n; do{ slow = bitSquareSum(slow); fast = bitSquareSum(fast); fast = bitSquareSum(fast); }while(slow != fast); return slow == 1; } };
縱一葦之所如,臨萬頃之茫然。