Computer Science, asked by sachinkimages, 1 year ago

Write a program in java to count no. of digits of a given number? (logic mainly)

Answers

Answered by VedaantArya
1

1.

int curr = n;

int counter = 1;

Create a while loop that checks if curr/10 >= 1.

If it is, set curr to curr divided by 10 and increment counter.

When the loop exits (that is, curr/10 < 1), return counter, which should indicate the number of digits (assuming that 0 is counted to be a one-digit number).

To remove the zero-possibility, add an if-then statement in the beginning.

2.

Convert the given number to a string using Integer.toString(n).

Then, print the length of the string. Simple.

Again, to remove the zero-possibility, add an if-then statement in the beginning.

Note that you'd probably be first taking the input as a string and then converting it to an integer - no need to do that in this method, and no need to do the first bit either - simply return the length of the string.

(length of the string is given by S.length())

3.

If in syllabus, use the logarithmic function (base 10) and simply return (characteristic + 1) as the number of digits.

4.

Another technique, but sort-of weird.

int count = 0;

/*pseudocode*/

while(num >= 10 ^ count)  {

   count++;

}

return count;

Note that this last one needs a little tweaking to get the right result - but you get the idea.

The above methods may misbehave with decimal numbers.

Similar questions