how do i get digits of an int?
i want to input a 3 digit int and to be able to print every digit individually
13 Replies
if the input is 475 u i want to be able to print every digit alone
Good morning, a quick way to solve this is as so:
The alternative is to use modulo and division in a loop. Harder to reason about, but no string conversion needed
I have to keep it as an int
I forgot to mention that
then try modulo/div
@Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa If you struggle I suggest learning about number systems
our typical decimal system, is a base 10 number system. you can apply a rule which is true for all number systems, if you keep doing modulo of the base of a number system, which is 10 here, and take the rest of it, you get a signle digit of the number in that respective number system
457 % 10 = 7
457 / 10 = 45
45 % 10 = 5
45 / 10 = 4
4 % 10 = 4
now if we take the solutions of the modulo operations, in other word the Rests of the calculation, and write it from bottom to top, we end up with the solution in desired number system:
457
this works for any number system. If you wanna convert number to binary, take 2 as base instead of 10. If you want to convert to hexadecimal, take 16 as base instead of 10 etc.
Oh
Before I read this I was close
I didn't know how to do the rest after the first one
I just did this
Thx
Now I actually understand
you're welcome 😊
I have another question
What's wrong with this?
Idk what to do
I need to confirm that the int has 4 digits