[Swift]LeetCode1017. 负二进制转换 | Convert to Base -2
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10634364.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Given a number N
, return a string consisting of "0"
s and "1"
s that represents its value in base -2
(negative two).
The returned string must have no leading zeroes, unless the string is "0"
.
Example 1:
Input: 2
Output: "110"
Explantion: (-2) ^ 2 + (-2) ^ 1 = 2
Example 2:
Input: 3
Output: "111"
Explantion: (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3
Example 3:
Input: 4
Output: "100"
Explantion: (-2) ^ 2 = 4
Note:
0 <= N <= 10^9
给出数字 N
,返回由若干 "0"
和 "1"
组成的字符串,该字符串为 N
的负二进制(base -2
)表示。
除非字符串就是 "0"
,否则返回的字符串中不能含有前导零。
示例 1:
输入:2 输出:"110" 解释:(-2) ^ 2 + (-2) ^ 1 = 2
示例 2:
输入:3 输出:"111" 解释:(-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3
示例 3:
输入:4 输出:"100" 解释:(-2) ^ 2 = 4
提示:
0 <= N <= 10^9
8ms
1 class Solution { 2 func baseNeg2(_ N: Int) -> String { 3 var num = N 4 var str = "" 5 var base = -2 6 while num < 0 || num >= 2 { 7 var q = Int(num / base) 8 if num < 0, num % base != 0 { q += 1 } 9 str = "\((num - q * base))\(str)" 10 num = q 11 } 12 if num != 0 { 13 str = "\(num)\(str)" 14 } 15 if str.isEmpty { 16 str = "0" 17 } 18 return str 19 } 20 }
Runtime: 16 ms
Memory Usage: 18.9 MB
1 class Solution { 2 func baseNeg2(_ N: Int) -> String { 3 var N = N 4 var ans:String = String() 5 while(N != 0) 6 { 7 var r:Int = abs(N % 2) 8 if r != 0 { N -= 1} 9 var q:Int = N / -2 10 ans.append((r + 48).ASCII) 11 N = q 12 } 13 ans = String(ans.reversed()) 14 if ans.isEmpty 15 { 16 ans.append("0") 17 } 18 return ans 19 } 20 } 21 22 //Int扩展 23 extension Int 24 { 25 //Int转Character,ASCII值(定义大写为字符值) 26 var ASCII:Character 27 { 28 get {return Character(UnicodeScalar(self)!)} 29 } 30 }