202.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.
class Solution {
public:
bool isHappy(int n) {
int i = 0;
int sum = 0;
//设定阈值,防止过度迭代,此处应当有数学证明,然而。。。
while(i < 30){
sum = sqrsum(n);
printf("%d\n",sum);
if(sum == 1)
return true;
i++;
n = sum;
}
return false;
}
//返回n的各位数的平方和
int sqrsum(int n){
int i=0;
int sum = 0;
while(n >= 10){
i = n%10;
n = n/10;
sum += i*i;
}
sum += n*n;
return sum;
}
};
206.Reverse a singly linked list.
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//迭代法求解列表逆序
ListNode*rhead = NULL;
if (NULL == head || NULL == head->next) {
return head;
}
while(head!=NULL){
ListNode*temp = head->next;
head->next = rhead;
rhead = head;
head = temp;
}
return rhead;
}
};
6 ZigZag Conversion
The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
class Solution {
public:
string convert(string s, int numRows) {
int l = s.size();
if (l == 0 || numRows <= 1) return s;
//ans存储每一行内容,row表示行数,d表示沿某个方向前进一步
string ans[numRows];
int row = 0, d = 1;
for(int i = 0; i < l; i++){
ans[row] += s[i];
row += d;
//到达最后一行则反向
if (row >= numRows) {
row = numRows-2;
d = -1;
}
//到达首行则反向
if (row < 0) {
row = 1;
d = 1;
}
}
string ret = "";
for (int i = 0; i < numRows; i++) {
ret += ans[i];
}
return ret;
}
};