Extract Digits of a Number
Problem Statement
1Problem Description :2Given a number, print all digits present in the number34Example 1 :5 Input : n = 1536 Output : 1, 5, 37 Explanation : 1, 5 and 3 are digits present in number 15389Example 2 :10 Input : n = 12111 Output : 1, 2, 112 Explanation : 1, 2 and 1 are digits present in number 121.
Procedure
To understand the logic, lets consider given number as 153. For given number, we can easily find out the digit present at units place by dividing the number by 10.
Step 1: number = 153
Step 2: when we divide the number by 10, we get remainder as 3 which is the digit at 1’s place and 15 is the quotient after dividing the number by 10.
Step 3: Now we need to get remaining digits other than 3, so we can update number as number/10 (i.e., quotient which we got in step2) and we again divide the number by 10 which will give remainder as 5 and quotient as 1.
Step 4: Now we consider the number as 1 and again we divide the number by 10, we get remainder as 1 and quotient as 0. i.e., so the procedure gets stopped here and we have extracted all digits of the given number.
Algorithm
1Input : An Integer n2Step 1: Start3Step 2: Read number n4Step 3: If number not equal to 0 Go to Step 4 , else Go to Step 85Step 4: digit = number % 106Step 5: number = number / 107Step 6: print digit8Step 7: Repeat Step 39Step 8: Stop10Output: All digits of the given number should be printed
Flowchart
Code Implementation
- Java
- C
1import java.util.Scanner;23public class ExtractDigitsOfANumber {45 public static void main(String[] args) {6 Scanner sc = new Scanner(System.in);78 System.out.print("Enter number : ");9 int number = sc.nextInt();1011 while(number != 0){12 int digit = number % 10;13 number = number /10;14 System.out.printf("%d ", digit);15 }16 System.out.println();17 }18}
Output 1 :
1Enter Number : 6352Digits are : 5, 3, 6
Output 2 :
1Enter Number : 1212Digits are : 1, 2, 1