This commit is contained in:
parent
83c66fc158
commit
59d1cb7245
12
include/s0007_reverse_integer.hpp
Normal file
12
include/s0007_reverse_integer.hpp
Normal file
@ -0,0 +1,12 @@
|
||||
#ifndef S0007_REVERSE_INTEGER
|
||||
#define S0007_REVERSE_INTEGER
|
||||
|
||||
#include <queue>
|
||||
#include <cmath>
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
int reverse(int x);
|
||||
};
|
||||
|
||||
#endif
|
20
src/s0007_reverse_integer.cpp
Normal file
20
src/s0007_reverse_integer.cpp
Normal file
@ -0,0 +1,20 @@
|
||||
#include "s0007_reverse_integer.hpp"
|
||||
|
||||
int Solution::reverse(int x) {
|
||||
int r{0};
|
||||
std::queue<int> queue;
|
||||
|
||||
while (x != 0) {
|
||||
queue.push(x % 10);
|
||||
x = static_cast<int>((x - (x % 10)) / 10);
|
||||
}
|
||||
while (!queue.empty()) {
|
||||
if (r < INT_MIN / 10 || r > INT_MAX / 10) {
|
||||
return 0;
|
||||
}
|
||||
r = r * 10 + queue.front();
|
||||
queue.pop();
|
||||
}
|
||||
|
||||
return r;
|
||||
}
|
31
tests/s0007_reverse_integer.cpp
Normal file
31
tests/s0007_reverse_integer.cpp
Normal file
@ -0,0 +1,31 @@
|
||||
#include "s0007_reverse_integer.hpp"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
TEST(Problem7, Case1) {
|
||||
int i = 123;
|
||||
int o = 321;
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.reverse(i), o);
|
||||
}
|
||||
|
||||
TEST(Problem7, Case2) {
|
||||
int i = -123;
|
||||
int o = -321;
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.reverse(i), o);
|
||||
}
|
||||
|
||||
TEST(Problem7, Case3) {
|
||||
int i = 120;
|
||||
int o = 21;
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.reverse(i), o);
|
||||
}
|
||||
|
||||
TEST(Problem7, Case4) {
|
||||
int i = -2147483648;
|
||||
int o = 0;
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.reverse(i), o);
|
||||
}
|
Loading…
Reference in New Issue
Block a user