lc2-Add Two Numbers 發表於 2015-08-30 | 分類於 leetcode | 0 comments 1234567891011121314151617181920class Solution {public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { int carry=0; ListNode* res,*headptr; res=new ListNode(0); headptr=res; while(l1!=NULL||l2!=NULL){ int sum = (l1==NULL?0:l1->val)+(l2==NULL?0:l2->val)+carry; carry = sum/10; res->next=new ListNode(sum%10); res=res->next; l1=l1==NULL?NULL:l1->next; l2=l2==NULL?NULL:l2->next; } if(carry) res->next=new ListNode(1); return headptr->next; }};
lc258-Add Digits 發表於 2015-08-30 | 分類於 leetcode | 0 comments 123456class Solution {public: int addDigits(int num) { return num - ((num-1)/9)*9; }};
lc202-Happy Number 發表於 2015-08-30 | 分類於 leetcode | 0 comments 1234567891011121314151617181920212223#include <iostream>#include <vector>using namespace std;class Solution { vector<int> myVec;public: bool isHappy(int n) { if (std::find(myVec.begin(), myVec.end(), n) != myVec.end()) { if(n!=1) return false; } myVec.push_back(n); int sum=0,m; m=n; while(m){ sum+=(m%10)*(m%10); m/=10; } if(sum==1) return true; else return isHappy(sum); } };