【leetcode】happy number--easy

來源:互聯網
上載者:User

標籤:

如果一個數的每個位的整數的平方和等於1,則為happy number

Example: 19 is a happy number

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1
#include<iostream>#include<vector>#include <math.h>using namespace std;class Solution {public:    bool isHappy(int n) {        temp.insert(temp.begin(),n);   //把當前值加入到曆史路徑中        int r=addsquare(n,0);        if(r==1)   //如果已經達到了happy number的條件            return true;        else        {            for(vector<int>::iterator it=temp.begin();it!=temp.end();it++)    //如果沒有達到happy number的條件,那麼比較r值和曆史值是否重合            {                if(r==*it)                      return false;   //如果和曆史值重合了,則不是happy number            }            isHappy(r);   //如果和曆史結果沒有重合,則繼續往後計算        }        }private:    vector<int> temp;    int addsquare(int n,int r){            //char str[11];            //itoa(n,str,10);    //數字轉換為字串,10代表10進位            //int r=0;            //char *ptr=str;            //while(*ptr!=‘\0‘)            //{            //    r+=(*ptr-‘0‘)*(*ptr-‘0‘);            //    ptr++;            //}            //return r;        int tmp=n%10;        r+=tmp*tmp;        n=(n-tmp)/10;        if(n==0)            return r;        else            addsquare(n,r);        }};void main(){    Solution S;    int n;    cin>>n;    cout<<S.isHappy(n);}

 

【leetcode】happy number--easy

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.