+ 2

How to write this code?

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

29th Mar 2017, 12:03 PM
Abdulmalik
6 Respostas
+ 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.
29th Mar 2017, 12:14 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 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.
29th Mar 2017, 12:59 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 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
30th Mar 2017, 6:56 PM
Cyrus Ornob Corraya
Cyrus Ornob Corraya - avatar
+ 2
I got it Thank you🌺
29th Mar 2017, 1:40 PM
Abdulmalik
+ 1
reminder=num%10; num/=10; store the reminder in some array
29th Mar 2017, 12:12 PM
Vijeth Belle
Vijeth Belle - avatar
+ 1
no problem with specific digits but the problem to make program general it's can breaks any digits???
29th Mar 2017, 12:29 PM
Abdulmalik