Swift算法笔记-分子分母

/*
 我们知道分数由分子和分母组成,所以给定你两个正整数,第一的代表分子,第二个代表分母,你能不能把他们化作最简的形式输出?
 例:
 input:
 4 8
 out put:
 1/2
 */

//辗转相除法
func test(molecular:Int, denominator: Int){
    if molecular <= 0 && denominator <= 0 { return }
    let Commondivisor = getCommondivisor(number1: molecular, number2: denominator)
    print("the Greatest Common divisor is \(Commondivisor)")
    print("the minimalist is \(molecular / Commondivisor)/\(denominator / Commondivisor) ")
}

//递归
func getCommondivisor(number1: Int, number2: Int) -> Int {
    let remainder = number1 % number2
    if remainder == 0 {
        return number2
    } else {
        return getCommondivisor(number1: number2, number2: remainder)
    }
}

test(molecular: 100, denominator: 200)

/*
 我们都知道数字的分数形式化简,那当然我们还有字幕形式的分子分母化简,给你两个字母(都是合法的小写形式),请你输出他的最简形式
 例:
 input:
 a ab
 output:
 1/b
 */

//猜想:通过哈希表摘出分子分母分别的字母数量,然后进行删减最后拼装

func test(molecular:String, denominator: String){
    
    var mDic = [Character:Int]()
    var d = ""
    var m = ""
    
    //将分子添加入哈希表
    for mC in molecular.characters{
        if var a = mDic[mC] {
            a += 1
            mDic[mC] = a
        } else {
            mDic[mC] = 1
        }
    }
    
    //遍历分母对哈希表进行删改
    for dC in denominator.characters {
        if var a = mDic[dC] {
            if a != 0 {
                a -= 1
                mDic[dC] = a
            } else {
               d.append(dC)
            }
        } else {
            d.append(dC)
        }
    }
    
    //将哈希表删改后的数据填入分子字符串
    for (v,k) in mDic{
        for _ in 0..

output:

the Greatest Common divisor is 100
the minimalist is 1/2 
1 / bbb
Program ended with exit code: 0

你可能感兴趣的:(Swift算法笔记-分子分母)