Count of Digits:
–>Given a number n, the task is to return the count of digits in this number.
Example:
Input: n = 1567Output: 4Explanation: There are 4 digits in 1567, which are 1, 5, 6 and 7Input: n = 1567 Output: 4 Explanation: There are 4 digits in 1567, which are 1, 5, 6 and 7Input: n = 1567 Output: 4 Explanation: There are 4 digits in 1567, which are 1, 5, 6 and 7
Enter fullscreen mode Exit fullscreen mode
–>The idea is to count the digits by removing the digits from the input number starting from right(least significant digit) to left(most significant digit) till the number is reduced to 0.
–> We are removing digits from the right because the rightmost digit can be removed simply by performing integer division by 10. For eg: n = 1567, then 1567 / 10 = 156.7 = 156(Integer Division).
Flowchart:
Example:
package programs;public class CountOfDigit {public static void main(String[] args){int no = 54321;int count = 0;while(no>0){//System.out.println(no%10);//no = no/10;count = count+1;}System.out.println("count: "+count);}}package programs; public class CountOfDigit { public static void main(String[] args) { int no = 54321; int count = 0; while(no>0) { //System.out.println(no%10); //no = no/10; count = count+1; } System.out.println("count: "+count); } }package programs; public class CountOfDigit { public static void main(String[] args) { int no = 54321; int count = 0; while(no>0) { //System.out.println(no%10); //no = no/10; count = count+1; } System.out.println("count: "+count); } }
Enter fullscreen mode Exit fullscreen mode
Output:
1
2
3
4
5
count: 5
© 版权声明
THE END
暂无评论内容