[Swift Weekly Contest 130]LeetCode1028. 负二进制转换 | Convert to Base -2

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:

  1. 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:

扫描二维码关注公众号,回复: 5731911 查看本文章
输入:4
输出:"100"
解释:(-2) ^ 2 = 4 

提示:

  1. 0 <= N <= 10^9

Runtime: 8 ms
Memory Usage: 19.2 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 }

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10634364.html