Cody
Follow


Trick: Easy Digit Manipulation

goc3 on 5 Jun 2024 (Edited on 5 Jun 2024)
Latest activity Edit by Adam Danz on 7 Jun 2024

There are a host of problems on Cody that require manipulation of the digits of a number. Examples include summing the digits of a number, separating the number into its powers, and adding very large numbers together.
If you haven't come across this trick yet, you might want to write it down (or save it electronically):
digits = num2str(4207) - '0'
That code results in the following:
digits =
4 2 0 7
Now, summing the digits of the number is easy:
sum(digits)
ans =
13
Adam Danz
Adam Danz on 6 Jun 2024 (Edited on 7 Jun 2024)
So far this discussion has listed 3 unique ways to separate digits in a number. Someone should write up a comparison to see how all three handle edge cases.
  • large integers
  • negative values
  • fractional value
  • array of values
  • complex numbers
  • different numeric data types
Binbin Qi
Binbin Qi on 7 Jun 2024
This is a good idea. But MATLAB has no data type for large integers and fractional value, and which numbers should we get for complex numbers. So it is not the trick that gets digits from numbers. It needs a function that hold with different situations. However, you can submit a problem on Cody. I will do it as soon as possible.
goc3
goc3 on 6 Jun 2024
That is a good idea. I think such a comparison should also include performance, such as in a large for loop.
Binbin Qi
Binbin Qi on 6 Jun 2024
This is the best way to convert string to num for single demand.
However, if you want to string array which is huge to number, the method is not efficient.
You can use another way like this:
x =
123 5676
>> mod(floor(x'./10.^(3:-1:0)),10)
ans =
0 1 2 3
5 6 7 6
Adam Danz
Adam Danz on 6 Jun 2024 (Edited on 6 Jun 2024)
Clever
The 3 in the exponent is hard coded to work with the largest value in the array (5676) whose order of magnitude is 10^3.
If x contained a maximum value whose order of magnitude isn't 10^3 it would return incorrect results.
x = [123 10321]
mod(floor(x'./10.^(3:-1:0)),10)
ans =
0 1 2 3
0 3 2 1
Instead, you can replace 3 with floor(log10(max(x))) to find the maximum power needed.
mod(floor(x'./10.^(floor(log10(max(x))):-1:0)),10)
ans =
0 0 1 2 3
1 0 3 2 1
Chen Lin
Chen Lin on 5 Jun 2024
Thansk for sharing this trick!
Adam Danz
Adam Danz on 5 Jun 2024 (Edited on 5 Jun 2024)
I love this one!
Alternatively, without using num2str,
N = 4207;
digstr = dec2base(N,10) - '0'
digstr =
4 2 0 7
I learned this from @John D'Errico (link)