Coding Interview

coding interview questions part 2

Pinterest LinkedIn Tumblr

Reverse Integer

Reverse Integer reverses the given integer digits to reverse order. Example x=123 and output y=321.
This algorithm takes the integer value and reverses the order of given integer value.
Example:-
X = 123. The program should return 321.

Source Code

package com.dsacode.Probelms;

public class ReverseInteger {

	public int Reverse(int x){
		
		boolean flag = false;
		
		if(x < 0){
			x = 0- x;
			flag = true;
		}
		
		int res = 0;
		int p=x;
		
		while(p > 0 ){
			
			int mod = p % 10;
			p = p / 10;
			res = res * 10 + mod;
		}
		
		if(flag)
			res = 0 - res;
		
		return res;
	}
	
	public int simpleReverse(int x){
		String stringinput = new Integer(x).toString();
		String reversed = new StringBuilder(stringinput).reverse().toString();
		return Integer.parseInt(reversed);
	}
	
	public static void main(String[] args) {
		ReverseInteger obj = new ReverseInteger();
		System.out.println("Reverse the 1534 integer :"+ obj.Reverse(1534));
		System.out.println("Reverse the 1534 integer using String functions:"+  obj.simpleReverse(1534));
	}

}

#include "stdafx.h"

#include < stdio.h >
#include < iostream >
using namespace std;

 int Reverse(int x){

	bool flag = false;

	if (x < 0){
		x = 0 - x;
		flag = true;
	}

	int res = 0;
	int p = x;

	while (p > 0){

		int mod = p % 10;
		p = p / 10;
		res = res * 10 + mod;
	}

	if (flag)
		res = 0 - res;

	return res;
}

int _tmain(int argc, _TCHAR* argv[])
{
	cout << "Reverse the 1534 integer :" << Reverse(1534) << endl;
	cout << "Reverse the 1534 integer using String functions:" << Reverse(1534) << endl;

	return 0;
}

Output

Reverse the 1534 integer :4351
Reverse the 1534 integer using String functions:4351

Algorithm Explanation

Take the number and check whether positive or negative.
If the number is negative, convert to positive number and take remainder mod.
Loop through all the digits and reverse each digit.
Add negative if the number is negative and Return the result.
1 2 3 4 5

Write A Comment