4 ms·
What's the elegant mathematical way to do this? I learned engineering school programming (read: programming with no standards or formal theory whatsoever) and t
by quacked 6y ago
What's the elegant mathematical way to do this? I learned engineering school programming (read: programming with no standards or formal theory whatsoever) and the only thing that's coming to mind is num2str/split/multiply/concatenate/str2num, but that seems too easy for a real programming interview.
- linuxftw 6y agoYou can detect each digit like this: For example, take 999 (N). Using only math, how can I determine the value of each digit? (be sure to take abs(N) and record value of N/abs(N) for later) res = N - (N - 1). Digit = res + 1; If Digit == 10, Digit = 0. So, given that function to find each digit, you can build a loop using 10^i to detect each digit (subtracting the sum of all preceding digits and dividing by 10^i to trim the lower order digits you've already resolved). We'll need a place to store each digit, such as an array. Of course, this assumes integers in base 10. If they are another base (8, 16), replace the 10^i above with the base. It's also ambiguous as to if the function should just return a concatenated version of the results or some possibly a sum. In any case, using a cast to string would be way easier.
- quacked 6y agoThanks!
- pmiller2 6y agoIf you want to be tricky about it, you can do it in one line in Python. Let d be your original integer. Then [(d%10**(n+1) - d%10**n) / 10**n for n in reversed(xrange(int(log10(d)+1)))] will be a list containing the base 10 digits of d as integers. Technically, you need to do from math import log10 to make this work, but you can fit that on the same line with a little hacking around using __import__, such as this quick and very dirty attempt: [ [(d%10**(n+1) - d%10**n) / 10**n for n in reversed(xrange(int(log10(d)+1)))] for log10 in [__import__("math", fromlist=["log10"]).log10]][0] Edit: Just to carry this a little further, if we interpret "a new integer that's the result of each of the original integer's digits squared" as doing something like this: 129 -> 1481 (i.e. 9 gets replaced with 81), then we can do it in one line like this: int(''.join([str(x**2) for x in [(d%10**(n+1) - d%10**n) / 10**n for n in reversed(xrange(int(log10(d)+1)))]]))
- quacked 6y agoOoh, nice.
- zadkey 6y agoWell the mathematical way of doing this involves doing a Mod 10 to pull off a digit and then incrementing a number that multiples the mod 10. I've also seen incrementing an exponent. And I hear from more math oriented people that there are other ways.