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:
importjava.util.LinkedList;importjava.lang.Integer;importjava.io.*;publicclassIntToList{privateLinkedList<Integer>converted;privateIntegertoBeConverted;publicstaticvoidmain(String[]argv){// Create a IntToList Object to use during conversionIntToListobj;// Create a buffered reader to read the integerBufferedReaderin=newBufferedReader(newInputStreamReader(System.in));// To be used to get the input of a fileStringinput;System.out.printf("%s: ","Please enter an integer to convert");try{// Read in the user inputinput=in.readLine();// Convert the string to an int using library functionsobj=newIntToList(Integer.valueOf(input));obj.convertToList();obj.printList();}catch(NumberFormatExceptionN){// Catch a non-integer input or too large inputSystem.out.printf("%s\n","Please enter an integer.");}catch(ExceptionE){// Everything elseE.printStackTrace();}return;}publicIntToList(Integerinput){// InitializationstoBeConverted=input.intValue();converted=newLinkedList<Integer>();}publicvoidconvertToList(){inttemp=toBeConverted.intValue(),remainder;// Once the integer is equal to zero, there are no more single digits to extractwhile(temp>0){// This remainder will be committed to the list of integersremainder=temp%10;// This will add the integer to the front of the listconverted.addFirst(newInteger(remainder));// This will remove a power of 10 from the read in integer, casted to not be a doubletemp=(int)Math.floor(temp/10);}}publicvoidprintList(){System.out.print("Converted Integer to List: ");// Print out all the single digits in the listfor(Integeri:converted){System.out.print(i);}System.out.print("\n");}}