在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a number The returned string must have no leading zeroes, unless the string is Example 1: Input: 2
Output:
Example 2: Input: 3
Output: Explantion: (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3
Example 3: Input: 4
Output: Explantion: (-2) ^ 2 = 4
Note:
给出数字 除非字符串就是 示例 1: 输入:2 输出:"110" 解释:(-2) ^ 2 + (-2) ^ 1 = 2 示例 2: 输入:3 输出:"111" 解释:(-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3 示例 3: 输入:4 输出:"100" 解释:(-2) ^ 2 = 4 提示:
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 }
|
请发表评论