版权声明:虽然写的很菜,但我也是有版权的! https://blog.csdn.net/weixin_42093825/article/details/83512968
题目:给定一个 32 位有符号整数,将整数中的数字进行反转。如果反转后的整数溢出,则返回 0。
解法一(我自己的沙雕解法)
思路:这还是我想了一小时想出来的,真的是。将一个整数按正负分类,然后每次除以10取余放入字符串中,这样输出刚好是反转。关于溢出的问题,给定的是int32,所以可以强制转换成int64,如果两个数相等就说明没有溢出。
int转换成string还是要用转换函数的。
// practice.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
#include "pch.h"
#include <iostream>
#include <string>
typedef int32_t int32;
typedef int64_t int64;
using namespace std;
int main()
{
int64 x;
cin >> x;
int64 y = int32(x);
if (x != y)
{
cout << "溢出!" << endl;
}
else
{
if (x >= 0)
{
string str1;
while (x)
{
str1 += to_string(x % 10);
x = x / 10;
}
cout << str1 << endl;
}
else
{
string str2 = "-";
x = -x;
while (x)
{
str2 += to_string(x % 10);
x = x / 10;
}
cout << str2 << endl;
}
}
}
好的解法:
利用每次的取余*10+取余就是反转
typedef int32_t int32;
typedef int64_t int64;
class Solution{
public:
int reverseIntegere(int x){
int r=0; //存放反转整数
while(x!=0)
{
int next = r*10+x%10;
x = x/10;
if(next/10 != r) //
{
r = 0;
break;
}
r = next;
}
return r;
}
}
感谢各位小弟的教导。
大哥会继续努力。
排名31万