aboutsummaryrefslogtreecommitdiff
path: root/challenge-192/mohammad-anwar/swift/ch-1.swift
blob: 3677ed01a9a7d526d5ba63fe6cf7f74c201b1b59 (plain)
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
46
47
48
49
50
51
52
53
54
import Foundation

/*

Week 192:

    https://perlweeklychallenge.org/blog/perl-weekly-challenge-192

Task #1: Binary Flip

    You are given a positive integer, $n.

    Write a script to find the binary flip.

ACTION:

     $ swift ch-1.swift 5
     $ swift ch-1.swift 4
     $ swift ch-1.swift 6

*/

enum ParamError: Error {
    case missingNumber
    case invalidNumber
}

do {
    let paramCount:Int = Int(CommandLine.argc)

    if paramCount <= 1 {
        throw ParamError.missingNumber
    }

    let num:Int = Int(CommandLine.arguments[1])!
    if num > 0 {
        let binary:String  = String(num, radix: 2)
        var flipped:String = ""
        Array(binary).forEach{ flipped += ($0 == "0") ? "1" : "0" }
        print(Int(flipped, radix: 2)!)
    }
    else {
        throw ParamError.invalidNumber
    }
}
catch ParamError.missingNumber {
    print("Missing number.")
}
catch ParamError.invalidNumber {
    print("Invalid number.")
}
catch let error {
    print(error)
}