Program opened below. You can scroll through the algorithm, Java code and output.

Fascinating Number

Download .java

Question

Determine whether concatenating n, 2n and 3n contains each digit from 1 to 9 exactly once (with no zero).

Step 1: Start and accept the positive integer. Step 2: Check that the input has three digits. Step 3: Calculate twice the original number. Step 4: Calculate three times the original number. Step 5: Concatenate the three values in their given order. Step 6: Count the characters in the combined representation. Step 7: Reject any combined result not containing exactly nine digits. Step 8: Create an array of ten Boolean flags. Step 9: Initialize a validity flag to true. Step 10: Inspect each concatenated digit in turn. Step 11: Reject digit zero because only one through nine are permitted. Step 12: Reject any digit already encountered. Step 13: Otherwise mark that digit as seen. Step 14: If no violation occurs, declare the number fascinating. Step 15: Display the classification and stop.
Java
import java.util.*;
class Fascinating {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        if (n < 100 || n > 999) {
            System.out.println("Not Fascinating");
            return;
        }
        String s = "" + n + (n * 2) + (n * 3);
        if (s.length() != 9) {
            System.out.println("Not Fascinating");
            return;
        }
        boolean[] seen = new boolean[10];
        boolean valid = true;
        for (int i = 0; i < s.length(); i++) {
            int digit = s.charAt(i) - '0';
            if (digit == 0 || seen[digit]) {
                valid = false;
                break;
            }
            seen[digit] = true;
        }
        System.out.println(valid ? "Fascinating" : "Not Fascinating");
    }
}
Input: 192 Output: Fascinating
← Previous Program 29 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.