数组的反转 偏执的太偏执、 2022-05-11 01:28 144阅读 0赞 **题目:** > 给定一个 32 位有符号整数,将整数中的数字进行反转。 **示例1:** > **输入:123** > > **输出:321** **示例2:** > **输入:-123** > > **输出:-321** **原理: ** > **利用栈的先进后出的原理,先将一个一个数压入栈中,出栈同时组合成所需结果。** > > **注意:范围限制以及符号判定等细节** #include<iostream> #include<string> #include<stack> #include<math.h> using namespace std; int reverse(int x) { int result = 0; stack<int> stack_x; int mod,bit = 0; bool flag = 0;//负数判断 if(x<0) { x = abs(x); flag = 1; if(x>pow(2,31))//32位负数最大值 return 0; } else if(x>(pow(2,31)))//32位最大值 return 0; //将数放入栈中 while(x) { mod = x %10; x = x /10; stack_x.push(mod); } //转化成数值 bit = stack_x.size(); //不能利用bit作条件,因为pop的存在 for(int i = 0; i < bit;i++) { result += (int(pow(10,i)))*(stack_x.top());//强制转换,因为pow结果为double型 stack_x.pop(); } if(flag)//负数判断 return -result; else return result; } int main() { int x; cout<<"输入一个有符号整数N:"; while(cin>>x) { cout <<"反转的结果:"<<reverse(x) <<endl; } system("pause"); return 0; }
还没有评论,来说两句吧...