Today's problem is a fun one. Without doing any casting or converting to an int, can you write a program that sums two strings? For bonus points try and make your code as compact as possible and submit your answer over at http://codegolf.stackexchange.com/questions/41833/sum-of-strings-without-converting.
Comments:
Derek - 9 years, 11 months ago
Well so I was going to use arrays of digits and modular math, but I realized that getting the index of a digit was an implicit integer conversion. I also realized that relying on the relative positions of the characters in the code page was cheating as well. I couldn't do a lookup table from digit to an index into an array, because that's yet another integer conversion.
So, to add digits, I drew inspiration from my electrical engineering classes. I used two 2-D lookup hashes to compute each possible sum, one for each value of the carry bit.
I then recursively add each character in each string, starting at the left and working to the right, saving the carry value as I go.
The only adding performed is string concatenation.
I originally toyed with doing a tens-complement conversion to handle the adding of negative numbers, but I decided I'm not that patient.
There are probably smarter ways to do this but I'm done. Hope it works.
reply permalink