Untitled

mail@pastecode.io avatar
unknown
swift
12 days ago
1.5 kB
1
Indexable
Never
import Foundation

enum SolutionError: String, Error {
    case characterError = "Please provide only 0 or 1"
    case convertStringError = "Can't convert string to int"
    case intValueNotAllowable = "Converted binary string is not allowable"
}

final class SolutionHelper {
    static func containsOnlyBinaryCharacters(_ input: String) -> Bool {
        let binaryCharacterSet = CharacterSet(charactersIn: "01")
        return input.unicodeScalars.allSatisfy { binaryCharacterSet.contains($0) }
    }
    
    static func convertBinaryStringToInt(value: String) -> Int? {
        guard let value = Int(value, radix: 2) else {
            return 0
        }
        return value
    }
    
    static func isIntAllowable(value: Int) -> Bool {
        value >= 1 && value <= 1_000_000
    }
}

public func solution(_ S : inout String) throws -> Int {
    guard SolutionHelper.containsOnlyBinaryCharacters(S) else {
        throw SolutionError.characterError
    }
    
    guard var value = SolutionHelper.convertBinaryStringToInt(value: S) else {
        throw SolutionError.convertStringError
    }
    
    guard SolutionHelper.isIntAllowable(value: value) else {
        throw SolutionError.intValueNotAllowable
    }
    
    var operations = 0
    
    while value > 0 {
        if value % 2 == 0 {
            value /= 2
        } else if value % 2 != 0 {
            value -= 1
        }
        operations += 1
    }
    
    return operations
}


var str = "1111010101111"
print(try solution(&str))
Leave a Comment