美文网首页
IOS 算法(基础篇) ----- 十-二进制数的最少数目

IOS 算法(基础篇) ----- 十-二进制数的最少数目

作者: ShawnAlex | 来源:发表于2021-04-14 21:38 被阅读0次

如果一个十进制数字不含任何前导零,且每一位上的数字不是 0 就是 1 ,那么该数字就是一个 十-二进制数 。例如,101 和 1100 都是 十-二进制数,而 112 和 3001 不是。
给你一个表示十进制整数的字符串 n ,返回和为 n 的 十-二进制数 的最少数目。

例子:

输入:n = "32"
输出:3
解释:10 + 11 + 11 = 32

输入:n = "82734"
输出:8

输入:n = "27346209830709182346"
输出:9

解题思路

别看题意很长很繁琐, 其实就是找到字符串中的最大数(细品下:))

代码

方法1

class Solution {
    func minPartitions(_ n: String) -> Int {
        if n.contains("9") { return 9 }
        else if n.contains("8") { return 8 }
        else if n.contains("7") { return 7 }
        else if n.contains("6") { return 6 }
        else if n.contains("5") { return 5 }
        else if n.contains("4") { return 4 }
        else if n.contains("3") { return 3 }
        else if n.contains("2") { return 2 }
        else if n.contains("1") { return 1 }
        return 0
    }
}

方法2

class Solution {
    func minPartitions(_ n: String) -> Int {
        return n.compactMap{ str in Int(String(str))}.max()!
    }
}

方法3

class Solution {
    func minPartitions(_ n: String) -> Int {
       let temp = n.sorted(), lastStr = String(temp.last!)
       return Int(lastStr)!
    }
}

题目来源:力扣(LeetCode) 感谢力扣爸爸 :)
IOS 算法合集地址

相关文章

网友评论

      本文标题:IOS 算法(基础篇) ----- 十-二进制数的最少数目

      本文链接:https://www.haomeiwen.com/subject/bunllltx.html