aboutsummaryrefslogtreecommitdiff
path: root/Java/Beginer training/src/VampireNumber.java
blob: 63d70858715d112126caf5e75bb06e00b0f60f0a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class VampireNumber {
    public static void main(String args[]){
        //NOTE: Works ONLY with 4 digit numbers, for bigger use BigVampireNumber
        System.out.println(FindVampireNumber(6880));
    }

     public static String FindVampireNumber(int result){
        String num = result + "";
        int first = num.charAt(0) - 48, second = num.charAt(1) - 48, third = num.charAt(2) - 48, fourth = num.charAt(3) - 48;

        for (int i = 0; i < 4; i++){
            for (int j = 0; j < 3; j++){
                int first_half = Combine(first, second), second_half = Combine(third, fourth);
                int swapped_first_half = Combine(first, fourth), swapped_second_half = Combine(third, second);

                if (first_half * second_half == result) {
                    return result + " = " + first_half + " * " + second_half;
                }
                else if (swapped_first_half *swapped_second_half == result){
                    return result + " = " + swapped_first_half + " * " + swapped_second_half;
                }

                switch (j) {
                    case 0:
                    case 1:
                    int temp = fourth;
                        fourth = second; second = temp;
                        temp = third;
                        third = fourth; fourth = temp;

                        break;
                    case 2:
                        temp = second;
                        second = first; first = temp;
                        break;
                }
            }
        }
        return result + " isn't a vampire number";
    }

    private static int Combine(int first, int second) {
        return (first * 10) + second;
    }
}