How to break and integer into an array output.

146 views (last 30 days)
hello world
hello world on 1 Dec 2014
Commented: Walter Roberson on 23 Dec 2020
I need to build a function that turns an inputted integer into an array. An example is inputInteger = 9876 solution_array = [9 8 7 6] I have a code that works, however, I need it to work without the use of most built-in functions such as mod and possibly even floor. I can however use numel and zeros.
This is the code I have so far:
function solution_array = breakN2digits(inputInteger)
digits =floor(log10(inputInteger)) + 1;
if inputInteger >= 0
solution_array = zeros();
for i=digits:-1:1
solution_array(1,digits+1-i) = floor(inputInteger/(10^(i-1)));
inputInteger = mod(inputInteger,10^(i-1));

Answers (3)

Azzi Abdelmalek
Azzi Abdelmalek on 1 Dec 2014

Sign in to comment.

Pratik Bajaria
Pratik Bajaria on 1 Dec 2014
One of the easiest way to do this is fooling the way around.
First convert the number into string. Then run a simple for loop to attain every character, and then finally convert them back to number at the time of allocation.
A simple code to the above algorithm is as shown below.
for i=1:numel(xstr)
Please let me know in case of any doubts.
Regards, Pratik

Walter Roberson
Walter Roberson on 23 Dec 2020
If you cannot use floor or mod:
check whether the number is less than zero and if so error (because you cannot convert a negative sign into a digit)
Take uint64 of the number. If the number was double precision and greater than 2^53 then it might not have an exact double precision representation. If the number is greater than 2^64-1 then you are going to have problems doing the conversion using this approach.
Now loop. Divide the current value V by uint64(10) and remember the result Q. Multiply the result Q by uint64(10) giving Q10. Compare Q10 to the original value. If Q10 is greater than V then subtract uint64(1) from Q and uint64(10) from Q10. Now R = V - Q10 is the current last digit, put it at the beginning of the output array. Then assign Q to V. Keep looping until V is 0.
You are probably wondering why you have to do that test about larger than the original. It is because when you do division with integer values, the resulting output rounds rather than truncating. So uint64(37)/uint64(10) does not give 3, it gives 4. 4*10 would then be greater than the original number and that tells you that rounding occurred so reduce the 4 to 3 and the 40 to 30, and then you have 37-30 = 7 is the last digit and 3 is what is left to convert
Walter Roberson
Walter Roberson on 23 Dec 2020
Yes, there are fairly different algorithms available.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!