Found Objects

find | egrep '\.(c|cpp|java|sh)$'

An Interview Question

Here’s one of the (admittedly easy) questions I received during an interview at Palantir:

Write a function that will convert an integer into a list of single digits.

So, how do you separate individual digits out of an integer? Simply put, division.

Say we had the number 112095. If we divide this number by 10 we achieve 11209.5 or 11209 remainder 5. The remainder will allow us to isolate the least significant digit. The main idea lies within taking the modulus of the original number by 10.

This is a quick java program I wrote up that accomplishes this:

(IntToList.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import java.util.LinkedList;
import java.lang.Integer;
import java.io.*;

public class IntToList {

  private LinkedList<Integer> converted;
  private Integer toBeConverted;


  public static void main(String [] argv) {

	// Create a IntToList Object to use during conversion
	IntToList obj;
	
    // Create a buffered reader to read the integer
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    // To be used to get the input of a file
    String input;
    System.out.printf("%s: ","Please enter an integer to convert");

    try {
      // Read in the user input
      input = in.readLine();

      // Convert the string to an int using library functions
      obj = new IntToList(Integer.valueOf(input));

      obj.convertToList();
      obj.printList();

    } catch (NumberFormatException N) {  // Catch a non-integer input or too large input
  	  System.out.printf("%s\n","Please enter an integer.");
    } catch (Exception E) { // Everything else
      E.printStackTrace();
    }

    return;

  }

  public IntToList(Integer input) {
	  // Initializations
	  toBeConverted = input.intValue();
	  converted = new LinkedList<Integer>();
  }

  public void convertToList() {

    int temp = toBeConverted.intValue(), remainder;

    // Once the integer is equal to zero, there are no more single digits to extract
    while(temp > 0) {
    	
      // This remainder will be committed to the list of integers
      remainder = temp % 10;

      // This will add the integer to the front of the list
      converted.addFirst(new Integer(remainder));

      // This will remove a power of 10 from the read in integer, casted to not be a double
      temp = (int)Math.floor(temp / 10);
    }

  }

  public void printList() {
	
    System.out.print("Converted Integer to List: ");
	
    // Print out all the single digits in the list
    for (Integer i : converted) {
    	System.out.print(i);
    }

    System.out.print("\n");

  }

}