# Reverse Integer

• Solution by ratnesh.katiyar-gmail.com
Algorithm
The idea is to store previous value of the sum can be stored in a variable which can be checked every time to see if the reverse overflowed or not.
'''
class Solution {

``````public:
int reverse(int num) {
bool negativeFlag = false;
if (num < 0)
{
negativeFlag = true;
num = -num ;
}

int prev_rev_num = 0, rev_num = 0;
while (num != 0)
{
int curr_digit = num%10;

rev_num = (rev_num*10) + curr_digit;

if ((rev_num - curr_digit)/10 != prev_rev_num)
{

return 0;
}

prev_rev_num = rev_num;
num = num/10;
}

return (negativeFlag == true)? -rev_num : rev_num;
}
``````

};
'''
Complexity Analysis

• Time complexity : \$\$O(logn)\$\$.

• using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Reverse
{
class Program
{
static void Main(string[] args)
{
int x=-123;
int n;
n = Reverse(x);
}

``````    static public int Reverse(int x)
{
bool negativenumber = false;
if (x < 0)
{
x = -x;
negativenumber = true;
}
int y=0;
string strX;
strX = x.ToString();
char [] arraryX=strX.ToCharArray();
Array.Reverse(arraryX);
strX = new string(arraryX);
int.TryParse(strX,out y);

if (negativenumber)
return -y;
else
return y;
}
}
``````

}

• negativeFlag
class Solution {
public int reverse(int x) {
String str = String.valueOf(x);
String result = "0";
int k = 0;
if(str.startsWith("-")){
result = "-";
k = 1;
}
for(int i=str.length()-1;i>=k;i--){
result +=String.valueOf(str.charAt(i));
}
try{
return Integer.parseInt(result);
}catch(Exception e){
return 0;
}
}
}

• @leisenpin
class Solution {
public int reverse(int x) {
String str = String.valueOf(x);
String result = "0";
int k = 0;
if(str.startsWith("-")){
result = "-";
k = 1;
}
for(int i=str.length()-1;i>=k;i--){
result +=String.valueOf(str.charAt(i));
}
try{
return Integer.parseInt(result);
}catch(Exception e){
return 0;
}
}
}

• @ratnesh.katiyar-gmail.com Can you explain how the time complexity is log n?

• ``````        boolean negativeFlag = false;
if (x < 0) {
negativeFlag = true;
x = -x;
}

Long rcvNum = 0L;
while (x != 0) {
int leftNum = x % 10; //求余
rcvNum = rcvNum * 10 + leftNum;
x = x / 10; //取整
}

rcvNum = negativeFlag ? -rcvNum : rcvNum;
if (rcvNum < Integer.MIN_VALUE || rcvNum > Integer.MAX_VALUE) {
return 0;
}

return rcvNum.intValue();
}
``````

• ``````    public static int reverse(int x) {
boolean negative = false;
if (x < 0) {
x = Math.abs(x);
negative = true;
}

ArrayList<Integer> tmp = new ArrayList<Integer>();
int n = x;
while (n != 0) {
n = n/10;
}
StringBuilder result = new StringBuilder();
if (negative == true) {
result.append('-');
}
for (int k: tmp) {
result.append(k);
}
int res;
try {
res = Integer.parseInt(result.toString());
} catch (NumberFormatException ex) {
return 0;
}
System.out.println(res);
return res;
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.