吹拉弹唱


  • Home
  • Archive
  • Categories
  • Tags
  • Books
  •  

© 2022 Kleon

Theme Typography by Makito

Proudly published with Hexo

Code - String

Posted at 2022-05-05Updated at 2022-05-05 interview  interview algorithm 

  • LeetCode
    • 166. Fraction to Recurring Decimal
    • 28. Implement strStr()

# LeetCode

# 166. Fraction to Recurring Decimal

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
func fractionToDecimal(numerator int, denominator int) string {
if numerator == 0 {
return "0"
}
ans := []byte{}
if (numerator > 0) != (denominator > 0) {
ans = append(ans, '-')
}
num := abs(numerator)
den := abs(denominator)
ans = append(ans, toByte(num / den)...)
rem := num % den
if rem == 0 {
return string(ans)
}
ans = append(ans, '.')
d := make(map[int]int)
for rem != 0 {
if index, exists := d[rem]; exists {
ans = append(ans[:index+1], ans[index:]...)
ans[index] = '('
ans = append(ans, ')')
break
}
d[rem] = len(ans)
rem *= 10
ans = append(ans, toByte(rem / den)...)
rem %= den
}
return string(ans)
}

func abs(x int) int {
if x < 0 {
return -x
}
return x
}

func toByte(x int) []byte {
return []byte(fmt.Sprintf("%v", x))
}

# 28. Implement strStr()

leetcode

1
2
3
4
5
6
7
8
9
10
func strStr(haystack string, needle string) int {
for i := 0; ; i++ {
for j := 0; ; j++ {
if j == len(needle) { return i }
if (i + j == len(haystack)) { return -1 }
if needle[j] != haystack[i + j] { break }
}
}
return -1
}

Share 

 Previous post: Code - Stack Next post: Code - Array 

© 2022 Kleon

Theme Typography by Makito

Proudly published with Hexo