leetcode练习三

本文介绍了一种使用C++对字符串进行N字形排列的方法,以及一种有效反转32位有符号整数各位数字的算法。通过具体代码示例,展示了如何处理字符串的复杂排列,并确保反转后的整数在32位范围内,超出范围则返回0。

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

6.对输入的一串字符串按连续的N字形排列,其输出为对排列好的N字形按从左到右,从上到下的顺序保存为字符串输出,numRols为N字形的行数
c++:

class Solution {
public:
    string convert(string s, int numRows) {
        int len = s.size();
        string res;
        if(s.empty() || numRows < 1)
        {
            return res;
        }
        if(numRows == 1)
        {
            return s;
        }

        vector<string> out(numRows);
        for(int i=0; i<len; i++)
        {
            int ans = i / (numRows-1);
            int cur = i % (numRows-1);
            if(ans % 2 == 0)
            {
                out[cur].push_back(s[i]);
            }
            else
            {
                out[numRows-cur-1].push_back(s[i]);
            }
        }
        for(int i=0; i<out.size(); i++)
        {
            res += out[i];
        }
        return res;
    }
};

7.给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。超过范围输出为0,首位不能为0;
c++: 8ms 8.8MB 我写的代码比较多但是条理清晰

class Solution {
public:
    int reverse(int x) {
        int max = 0x7fffffff, min = 0x80000000;

        int flag = 0;// 大于0
        if(x<0)
        {
            flag = 1;// 小于0
        }
        vector<int> out;
        long temp = x;
        if(flag != 0)
        {
            temp = -1*temp;// 转为正数
        }
        while(temp>0)
        {
            int temp1 = temp %10; // 求最低位的数
            out.push_back(temp1);
            temp = temp / 10;
        }
        long temp2 = 0;
        int j = out.size()-1;
        for(int i=0; i<out.size(); i++)
        {
            if(i == 0 && out[i] == 0)
            {
                j--;
                continue;
            }
            temp2 += out[i]*pow(10,j);
            j--;
        }
        if(flag != 0)
        {
            temp2 = -1*temp2;
        }
        if(temp2>max || temp2<min)
        {
            return 0;
        }
        return temp2;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值