Leetcode(1)-happy数

本文探讨了快乐数的概念及其判断方法,并介绍了如何使用迭代法实现链表反转的算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;  
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值