-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1256-EncodeNumber.go
More file actions
65 lines (54 loc) · 1.27 KB
/
1256-EncodeNumber.go
File metadata and controls
65 lines (54 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
// 1256. Encode Number
// Given a non-negative integer num, Return its encoding string.
// The encoding is done by converting the integer to a string using a secret function
// that you should deduce from the following table:
// <img src="https://assets.leetcode.com/uploads/2019/06/21/encode_number.png" / >
// 0 ""
// 1 "0"
// 2 "1"
// 3 "00"
// 4 "01"
// 5 "10"
// 6 "11"
// 7 "000"
// Example 1:
// Input: num = 23
// Output: "1000"
// Example 2:
// Input: num = 107
// Output: "101100"
// Constraints:
// 0 <= num <= 10^9
import "fmt"
func encode(num int) string {
return fmt.Sprintf("%b", num+1)[1:]
}
func encode1(num int) string {
helper := func (x int) string {
if x == 0 {
return "0"
}
res := []byte{}
for x > 0 {
m := x % 2
x /= 2
res = append([]byte{byte( m + '0' )}, res...)
}
return string(res)
}
res := helper(num + 1)
return res[1:]
}
func main() {
// Example 1:
// Input: num = 23
// Output: "1000"
fmt.Println(encode(23)) // 1000
// Example 2:
// Input: num = 107
// Output: "101100"
fmt.Println(encode(107)) // 101100
fmt.Println(encode1(23)) // 1000
fmt.Println(encode1(107)) // 101100
}