My first solution was as follows:

```
class Solution {
public:
int reverse(int x) {
char digits[11] = {0,0,0,0,0,0,0,0,0,0,0}, i;
int weight = 1000000000, temp = x, retval = 0;
if(x < 0){
weight = -weight;
}
for(i = 1; i <= 10; i++){
digits[i] = temp/weight;
temp %= weight;
if(i <= 9){
weight /= 10;
}
}
for(i = 1; i <= 10; i++){
if(digits[i] != 0){
temp = retval;
retval += digits[i]*weight;
if(weight > 0 && retval < temp){
return 0;
}else if(weight < 0 && retval > temp){
return 0;
}
}
if(retval != 0){
weight *= 10;
}
}
return retval;
}
};
```

The solution once got AC, but after compared to the reference solution, I found they're not all the same. For overflow cases my solution generates wrong answers.

Later I add some modifications to it, and it proves to be correct now.

```
class Solution {
public:
int reverse(int x) {
char digits[11] = {0,0,0,0,0,0,0,0,0,0,0}, i;
int weight = 1000000000, temp = x, retval = 0;
if(x < 0){
weight = -weight;
}
for(i = 1; i <= 10; i++){
digits[i] = temp/weight;
temp %= weight;
if(i <= 9){
weight /= 10;
}
}
for(i = 1; i <= 10; i++){
if(digits[i] != 0){
temp = retval;
retval += digits[i]*weight;
if(i == 10 && digits[i] == 2){//bugs once found here and below
if(weight > 0 && retval < temp){
return 0;
}else if(weight < 0 && retval > temp){
return 0;
}
}else if(i == 10 && digits[i] > 2 && (weight == 1000000000 || weight == -1000000000)){
return 0;
}
}
if(retval != 0){
weight *= 10;
}
}
return retval;
}
};
```