+ 2

# How to write this code?

How can I write a program that breaks a number into its digits(for any integer number)?

6 Answers

+ 19

Hint:
suppose the number is 1542
1542/10 gives 154, and 1542%10 gives 2
154/10 = 15, 154%10 = 4
15/10 = 1, 15%10 = 5
1/10 = 0, 1%10 = 1
Look, the remainders are basically the individual digits. And the quotients are the numbers which should be divided by 10 in next iteration. When you get 0 as the quotient, stop the process.

+ 16

Yes, it'll work fine for any number. For example, if the variable is n, keep dividing n by 10 using a loop until the quotient is 0. The remainders of each iteration are the digits.

+ 4

I don't know java. But I can give you a better solution. You don't even need to use loops.
Convert the number to string. like :
string str = num.ToString() (code is in C#)
Then each character (char) in that string is the broken digits. Time complexity of this method is O(1) but if you use the general algorithm for this process the time complexity will be O(n). That means my process is better, though it is not the valid one. ;P

+ 2

I got it
Thank you🌺

+ 1

reminder=num%10;
num/=10;
store the reminder in some array

+ 1

no problem with specific digits but the problem to make program general it's can breaks any digits???