202. Happy Number
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
解题思路:
这类题目主要是判断循环什么时候结束。只要平方和的数字有重复,那必然会进入死循环。所以要保存平方和数字。可以用C++原生态的map函数和set函数来处理。
这里我们采用C语言,我们分析happy number,不管输入多大的数字,几番操作下来如果还不是happy number,那么平方和必然收敛于1000以内。我们可以维护一个大小为1000的数组,比如a[56]=1表示在求happy number的过程中56这个平方和数字出现的次数为1。如果某一个数字出现的次数为2且还不是haapy numbers时,那必然导致无限循环。具体代码如下:
int squaresNumSum(int n)
{
int sum = 0;
while (n != 0)
{
int a = n % 10;
sum += a*a;
n = n / 10;
}
return sum;
}
bool isHappy(int n){
int flagArray[1000]={0};
if (n <= 0)
{
return false;
}
int res = squaresNumSum(n);
while (res != 1)
{
if (res < 1000)
{
flagArray[res] ++;
if (flagArray[res] > 1)
{
return false;
}
}
res = squaresNumSum(res);
}
return true;
}
204. Count Primes
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
解题思路:
此题采用埃拉托色尼筛选法效率最高。
1、先用一个队列表示n个数;
2、先将1从队列中删除,1不是质数;
3、读取当前队列中最小的数2并保存在集合中,,并将2的倍数从队列中删除;
4、读取当前队列中最小的数3并保存在集合中,,并将3的倍数从队列中删除;
5、读取当前队列中最小的数5并保存在集合中,,并将5的倍数从队列中删除;
以此类推,最后统计集合中数的个数,即为质数的个数。代码可参考思路编写。本人也是参考网上的解题说明才发现有这样的这样的一个算法。
206. Reverse Linked List
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
解题思路:典型的链表反转
递归:
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* res =NULL, *tail = NULL;
if (head == NULL )
{
return NULL;
}
if (head->next == NULL)
{
return head;
}
tail = head->next;
res = reverseList(head->next);
tail->next = head;
head->next = NULL;
return res;
}
循环:
struct ListNode* reverseList(struct ListNode* head){
if (head == NULL)
{
return head;
}
if (head->next == NULL)
{
return head;
}
struct ListNode* cur = NULL, *pre = NULL, *post = NULL;
cur = head->next;
head->next = NULL;
while(cur != NULL)
{
post = cur->next;
cur->next = head;
head = cur;
cur = post;
}
return head;
}