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;
}
};