Bloomberg LP Interview Question for Interns


Country: United States




Comment hidden because of low score. Click to expand.
5
of 5 vote

public class Test {
	public static int reverse(int num){
	    int result = 0;
	    while(num != 0){
	        result = result * 10 + num % 10;
	        num /= 10;
	    }
	    return result;
	}
	
	public static void main(String[] args){
		System.out.println(reverse(-12345));
		System.out.println(reverse(12345));
	}
}

Apparently, we have to ask the interviewer what should we do if the number will overflow after reversing.

- ravio September 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

If the interviewer tell me to throw an exception, I'll do the following.

#include <iostream>
#include <climits>

using namespace std;

class overflow {};

int reverse_int(int n) {
	auto r = 0;
	const int boundary = n > 0 ? INT_MAX / 10 : INT_MIN / 10;
	const int remainder = n > 0 ? INT_MAX % 10 : INT_MIN % 10;
	while (n) {
		auto digit = n % 10;
		if ((r > 0 && (r > boundary || r == boundary && digit > remainder)) ||
			(r < 0 && (r < boundary || r == boundary && digit < remainder))) {
			throw overflow();
		}
		r = r * 10 + digit;
		n /= 10;
	}
	return r;
}

- anonymous November 12, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

A recursive version:

void printReverse(int x){
    if (x< 0){
        cout <<"-";
        printReverse(-x);
    }
	else if (x< 10) cout <<x<<endl;
	else {
		cout <<x%10;
		printReverse(x/10);
	};
};

- ninhnnsoc November 14, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Why can't we just do
result = addExact(result * 10,num % 10);
in the first solution to throw exception, catch it and throw your own exception again if needed.

- palzarena November 14, 2014 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

int reversedigits(int num) {
    int newnum=0;
    int digit;
    while (num) {
          digit = num%10;
          num /= 10;
          newnum = newnum*10 + digit;
    }
    return newnum;
}

- iwanna September 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

public String reverseNumber(int number){
		String rerverseNumber="";
		while(number!=0){
			 int n=number%10;
			 number=number/10;
			 rerverseNumber+=n;
		}
		System.out.println(rerverseNumber);
		return rerverseNumber;

}

- sultan October 05, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here's some python code:

def max_place_value(x):
    '''max_place_value(x) - find the maximum place value in the integer, x'''
    if x == 0:
        return -1
    
    return max_place_value(x // 10) + 1

def reverse(x):
    '''reverse(x) - reverse the digits in the integer, x'''
    
    # store if x is negative or not
    if x < 0:
        neg = -1
    else:
        neg = 1
    
    x = abs(x)
    
    n = max_place_value(x)
    r_num = 0
    for i in range(0, n + 1):
        place_value = 10 ** (n - i)
        
        digit = x // place_value
        
        r_num += digit * 10 ** i
        x -= digit * place_value
    
    return r_num * neg

print(reverse(-4872345)) # outputs -5432784
print(reverse(10478)) # outputs 87401

- Anonymous September 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <string>
#inlclude <iostream>

void swap( char* a, char* b ){
char temp = (*a);
(*a) = (*b);
(*b) = temp;
}

int reverseInt( int a ){
std::string astr = std::to_string(a);
// reverse the string
for( int i = 0; i<astr.size()/2; ++i )
swap( &astr[i], &astr[astr.size()-i] );
return atoi(astr.c_str());
}

- Anonymous September 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <sstream>

using namespace std;


void outReverse(int val)
{
    stringstream s;
    s << val;

    //go to the end of the buffer
    s.seekg( 0, s.end );
    
    //init end position
    int pos = s.tellg();
    
    //iterate buffer in reverse order and out char
    while( --pos >= 0 )
    {
        s.seekg( pos );
        char c = s.peek();
        cout << c;
    }
    cout << endl;
}


int main()
{

    int val;
    cin >> val;
    
    outReverse(val);
    
   return 0;
}

- Oleksii September 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This code doesn't use memory for string allocation.

- Oleksii September 23, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

int reverse(int n)
{
        int nReverse = 0;

        do
        {
                nReverse *= 10;

                int lastDigit = n % 10;
                nReverse += lastDigit;

                n /= 10;
        } while (n != 0);

        return nReverse;
}

- darko.maksimovic September 24, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
#include<conio.h>
int main()
{int b=0,a;
scanf("%d",&a);
while (a)
{b=b*10+(a%10);
a=a/10;}
printf("%d",b);



}

- Anonymous September 24, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Python:

int1=12345
int(str(int1)[::-1])

- mathytime September 24, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Recursive method to print (not return).

// n is unsigned int.
print_reverse(uint n) {
    if (n == 0) return;
    r = n % 10;
    print_reverse(n/10);
    cout << r;
}

- Ubbus September 25, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Python

def reverse(n):
arr1 = list(str(n)) # arr1 = ['1','2','3','4','5']
length=len(arr1) # length = 5
arr2 = ['']*length # arr2 = ['', '', '', '', '']

for char in arr1:
arr2[length-1] = char
length = length -1
# arr2 = ['5','4','3','2','1']
output = ('').join(arr2) # output = 54321
return int( output )

- Anonymous September 29, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Below are two different Java methods to reverse the input of int:

public void reverseNumbers ( int input){
		StringBuilder stringInput = new StringBuilder ( String.valueOf(input));
		System.out.println(stringInput.reverse().toString());
	}
	
	
public void reverseNumbersTwo ( int input){
		String StringInput = String.valueOf(input);
		char [] charArrayOfInput = StringInput.toCharArray();
		for (int i =(charArrayOfInput.length-1); i>=0;i-- ){
			System.out.print(charArrayOfInput[i]);
		}

- Anonymous October 03, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Below are two different Java methods to reverse the input of int:

public void reverseNumbers ( int input){
		StringBuilder stringInput = new StringBuilder ( String.valueOf(input));
		System.out.println(stringInput.reverse().toString());
	}
	
	
public void reverseNumbersTwo ( int input){
		String StringInput = String.valueOf(input);
		char [] charArrayOfInput = StringInput.toCharArray();
		for (int i =(charArrayOfInput.length-1); i>=0;i-- ){
			System.out.print(charArrayOfInput[i]);
		}

- koeber99 October 03, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public String reverseNumber(int number){
		String rerverseNumber="";
		while(number!=0){
			 int n=number%10;
			 number=number/10;
			 rerverseNumber+=n;
		}
		System.out.println(rerverseNumber);
		return rerverseNumber;

}

- sultan October 05, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Is there any advantage in converting the number to string?? As far as I see both the approaches take O(n) time.

- srajavel@uci.edu October 17, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I also thought of a different approach. Please feel free to comment. I am open to feedback.

public class reverseNum {

	public static int reverse(int num){
		String numStr = String.valueOf(num);
		StringBuilder reversedStr = new StringBuilder();
		for (int i = numStr.length(); i > 0; i--){
			reversedStr.append(numStr.substring(i-1, i));
		}
		int reversedNum = Integer.parseInt(reversedStr.toString());
		return reversedNum;
		
	}
	
	public static void main(String[] args) {
		int testNum = 1234;
		reverse(testNum);
	}
}

- mayadi@smith.edu November 02, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I could also add a condition check for negative numbers.
So basically if 1st character (meaning substring(0,1)) is "-" then I changed the loop's stop condition to i>1.

- mayadi@smith.edu November 02, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

{{
int reverse(int num){
double result = 0;
while(num != 0){
result = result * 10.0 + static_cast<double>(num % 10);
num /= 10;
cout<<result<<", "<<num<<endl;
}
if(result >= static_cast<double>(INT_MAX)) return INT_MAX;
else return static_cast<int>(result);
}

}}

- Eric November 04, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <cstdlib>
#include <iostream>

using namespace std;

void reverse(int & n);
/*
 * 
 */

int main(int argc, char** argv) {

    int n;
    cout<<"Enter n: ";
    cin>>n;
    cout<<endl;
    
    reverse(n);
    
    cout<<"Reversed number is : "<< n << endl;
    return 0;
}

void reverse(int & n) {
    
    int r = 0;
    while(n > 0) {
        r = r * 10 + (n % 10);
        n /= 10; 
    }
    n = r;
}

- shone43 November 04, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class ReverseNumberPrinting {

	public static void main(String[] args) {
		int number = 12345;
		int reverseNumber = reverseit(number);
		System.out.println(reverseNumber);
	}

	private static int reverseit(int number) {
		// TODO Auto-generated method stub

		int reverse = 0;
		int temp;

		while (number != 0) {
			temp = number % 10;
			reverse = reverse*10 + temp;
			number = number / 10;
		}

		return reverse;

	}

}

- yv1989@outlook.com January 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int reverse(int num)
{
int digit,rev=0;
while(num>0)
{
digit=num%10;
rev=(rev*10)+digit;
num=num/10;
}
return rev;
}

- Vartika Dhawan January 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def reverseNumber(number)
  result = 0
  while (number > 0) do
    n = number % 10
    result = result * 10 + n
    number = number / 10
  end
  return result
end

- tkang1 January 21, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class Ideone
{
	public static void main( String[] args ){
           System.out.println(reverse(12345));
	}
	
	public static int reverse(int in)
	{
		String s = Integer.toString(in);
		String num="";
		for(int i = s.length()-1; i>=0; i--)
		{
			num = num + s.charAt(i);
		}
		return Integer.parseInt(num);
	}
}

- naomi.lijing@googlemail.com February 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int reverseDigits(int num)
{
    string s = to_string(num);
    reverse(begin(s), end(s));

    return stoi(s, 0, 10);
}

- Anonymous November 13, 2016 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More