1,整数反转
示例:
输入 | 输出 |
---|---|
123 | 321 |
-123 | -321 |
120 | 21 |
实现:
#include <iostream>
using namespace std;
#include <climits>//INT_MAX
int main()
{
int x=123;
int res=0;
do{
if(res>INT_MAX/10 || res<INT_MIN/10)//判断溢出
return 0;
res = res*10 + x%10;
}while(x/=10);
cout<<res<<endl;
}
2,回文数
示例:
输入 | 输出 |
---|---|
121 | 正序倒序都一样,是 |
-121 | 正序倒序不一样,不是 |
实现:
#include <iostream>
using namespace std;
#include <climits>//INT_MAX
//搞后一半就行 与前一半比较是否相等
int main()
{
bool ress=false;
int input=123321;
//当input<0,最后一位是0第一位也得是0,所以只有0
if(input<0 || (input%10==0 && input!=0))
return false;
int res=0;
do{
if(res>INT_MAX/10 || res<INT_MIN/10)//判断溢出
return false;
res = res*10 + input%10;
input/=10;
}while(input > res);
//当输入的长度为奇数 res/10去除中位的数字 最中间的数字不影响回文的判断
ress = (input == res || input ==res/10);
cout<<ress<<endl;
}
3,有效的括号
示例:
输入 | 输出 |
---|---|
(){}[] | 前后闭合,有效 |
({[[}) | 前后闭合,有效 |
{] | 前后不闭合,无效 |
实现:
int main()
{
string input="({[]})";
unordered_map<char,char> match = {{'(',')'},{'{','}'},{'[',']'}};
int n=0;
while(n<input.size())
{
cout<<"1"<<input[n]<<" "<<match[input[n]]<<" "<<input[n+1]<<endl;
if(match[input[n]] == input[n+1] && input[n+1] != '\0')
{
input.erase(n,2);//
n=-1;
}
n++;
}
cout<<!input.size()<<endl;
}
//辅助栈,效率高
#include <iostream>
using namespace std;
#include <unordered_map>
#include <string>
#include <stack>
int main()
{
string input="({[]})";
unordered_map<char,char> match = {{')','('},{'}','{'},{']','['}};
stack<char> re;
cout<<re.empty()<<endl;
bool result;
for(char in:input)
{
cout<<in<<" "<<match[in]<<endl;
if(in=='(' || in=='{' || in=='[')
re.push(in);
else
{
if(re.empty() || re.top() != match[in])
result=0;
else
re.pop();
}
}
result=re.empty();
cout<<result<<endl;
}