#include <stdio.h>标签:std,return,snprintf,--,sum,int,INT,buf,leetcode From: https://blog.51cto.com/u_15899033/5902967
#include <string.h>
#include <iostream>
#include <limits>
int reverse(int x) {
long sum = 0;
while (x) {
sum = sum * 10 + x % 10;
x = x / 10;
}
if (sum > std::numeric_limits<int>::max() || sum < std::numeric_limits<int>::min()) {
return 0;
}
return static_cast<int>(sum);
}
int reverse1(int x) {
static const char *MAX_INT_VALUE = "2147483647";
static const int MAX_INT_SIZE = 10;
bool positive = true;
char buf[32] = "";
if (x < 0) {
if (std::numeric_limits<int>::min() == x) {
return 0;
}
x = -x;
positive = false;
}
//std::string str = std::to_string(x); // 比snprintf更慢
snprintf(buf, sizeof(buf), "%d", x); // 慢
return 0;
char ch = 0;
int len = strlen(buf);
int i = 0;
int j = len -1;
if ((MAX_INT_SIZE == len) && buf[j] >= '3') {
return 0;
}
for (;i < j;i++,j--) {
ch = buf[i];
buf[i] = buf[j];
buf[j] = ch;
}
if (MAX_INT_SIZE == len) {
if (strcmp(buf, MAX_INT_VALUE) > 0) {
return 0;
}
}
if (true == positive) {
return atoi(buf);
}
return -atoi(buf);
}
int main() {
for (int i = -99999999;i <= 9999999;i++) {
reverse(i); // 3.317s
// reverse1(i); // 10.649s
}
return 0;
}