Skip to content

Commit 5c3b128

Browse files
authored
feat: add swift implementation to lcci problem: No.05.02 (doocs#2666)
1 parent 2b94218 commit 5c3b128

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

lcci/05.02.Binary Number to String/README.md

+18
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,24 @@ func printBin(num float64) string {
108108
}
109109
```
110110

111+
```swift
112+
class Solution {
113+
func printBin(_ num: Double) -> String {
114+
var num = num
115+
var ans = "0."
116+
117+
while ans.count < 32 && num != 0 {
118+
num *= 2
119+
let x = Int(num)
120+
ans.append("\(x)")
121+
num -= Double(x)
122+
}
123+
124+
return num != 0 ? "ERROR" : ans
125+
}
126+
}
127+
```
128+
111129
<!-- tabs:end -->
112130

113131
<!-- end -->

lcci/05.02.Binary Number to String/README_EN.md

+18
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,24 @@ func printBin(num float64) string {
115115
}
116116
```
117117

118+
```swift
119+
class Solution {
120+
func printBin(_ num: Double) -> String {
121+
var num = num
122+
var ans = "0."
123+
124+
while ans.count < 32 && num != 0 {
125+
num *= 2
126+
let x = Int(num)
127+
ans.append("\(x)")
128+
num -= Double(x)
129+
}
130+
131+
return num != 0 ? "ERROR" : ans
132+
}
133+
}
134+
```
135+
118136
<!-- tabs:end -->
119137

120138
<!-- end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution {
2+
func printBin(_ num: Double) -> String {
3+
var num = num
4+
var ans = "0."
5+
6+
while ans.count < 32 && num != 0 {
7+
num *= 2
8+
let x = Int(num)
9+
ans.append("\(x)")
10+
num -= Double(x)
11+
}
12+
13+
return num != 0 ? "ERROR" : ans
14+
}
15+
}

0 commit comments

Comments
 (0)