Code 4: Technique to count the number of digits in a number.

Problem Description: 
We are given a number(integer)as input we have to count the number of digits in that number. For example if the number is 123456 the number of digits is 6. Here we need to apply the technique called Digit Extraction. By which we will extract individual digits and then count them using a counter. In digit extraction the technique is pure mathematical, we will find the remainder on dividing the number by 10 without modifying the original number. Now as we know on dividing by 10 the remainder is always that in the ones place of the number. Example 123456%10 is 6. This way we will be able to get all the digits in a number in reverse order. Next we will divide the number by 10 and replace it with its quotient, as we know integers don't except decimal part, the last digit will be truncated. Example 123456/10, decimal result=12345.6 integer result=12345. Thus we would repeat the following until we transform the number to 0 as when the last digit is extracted the number left on dividing it with 10 will be 0. Example 1/10 integer result=0. Now for apply digit extraction we will require conditional looping as we have to continue until the number is not equal to 0. In C/C++ we will take the help of Do-While loop.

No comments:

Post a Comment