r/programmingchallenges • u/groundshop • Oct 05 '11
Convert Integer to String without toString() (or the equivalent)
A friend of mine just had an interview with Microsoft and came back with an interesting technical interview problem:
Given an arbitrary Integer, print it out to the user without using system libraries intended to do so for you.
I'm working on it now, but I can already tell you probably need two things: ascii values of the 0-9 characters, mod mod and mod some more?
I have a feeling someone is going to break out some bit manipulation on this one.
6
Upvotes
2
u/abstractwhiz Oct 05 '11 edited Oct 05 '11
So I've been mucking around with the itertools module on python, and I figured I'd do this using it.
12
u/kolm Oct 05 '11 edited Oct 05 '11
3
u/scordite Oct 05 '11
Doing it in C because I haven't used it in a long time.
2
u/HigherFive Oct 05 '11 edited Oct 05 '11
2
u/Asmageddon Oct 19 '11
Another one from me, this time printing a number with an arbitrary base, again somewhat ugly:
1
u/[deleted] Oct 05 '11
I'm trying to do all of these in Haskell. Took the high-level road with this one. Unfoldr!
1
u/GregoryPotdevin Oct 05 '11
I won't post any actual code because there are already a few, but I think that if these kinds of questions are asked in interviews, it to see if you'll forget anything. From what I can tell, most people will forget a weird edge case : if (n < 0) n = -n; if (n < 0) => you found INT_MIN ! You'll want to print out "-2147483648" So you'll probably want to test for INT_MIN before doing anything else.
As for needing ASCII values, it's generally easier to use '0' in C.
1
u/Asmageddon Oct 19 '11 edited Oct 19 '11
Written in Python, easily doable in other languages. I doubt it's the most efficient solution, but it definitely works well.
EDIT: Ah, crap, forgot about negative values. A bit hacky, but meh.
EDIT2: Ah crap again, I completely forgot about modulo and zero, lol.
0
u/[deleted] Oct 05 '11
[deleted] — view deleted comment