Skip to content

Commit

Permalink
review300: fraction to recurring decimal
Browse files Browse the repository at this point in the history
  • Loading branch information
meooxx committed Jul 20, 2024
1 parent 060a24e commit 2b983c8
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
49 changes: 49 additions & 0 deletions fractionToRecurringDecimal/review300.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package main

import "fmt"

func fractionToDecimal(numerator int, denominator int) string {
if numerator == 0 {
return "0"
}
neg := false
if numerator < 0 {
neg = true
numerator = -numerator
}
if denominator < 0 {
neg = !neg
denominator = -denominator
}
result := ""
fMap := map[int]int{}
d := numerator / denominator
n := (numerator % denominator) * 10
floatStr := ""
index := 1
for n > 0 && fMap[n] == 0 {
fMap[n] = index
if n > denominator {
floatStr += fmt.Sprint(n / denominator)
n = (n % denominator) * 10
} else {
floatStr += "0"
n *= 10
}
index++
}
if neg {
result = "-"
}
result += fmt.Sprint(d)
if floatStr != "" {
result += "."
}
if n > 0 {
result += fmt.Sprintf("%s(%s)", floatStr[:fMap[n]-1], floatStr[fMap[n]-1:])
} else {
result += floatStr

}
return result
}
1 change: 0 additions & 1 deletion fractionToRecurringDecimal/review_200_1.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ func fractionToDecimal(numerator int, denominator int) string {
if floatNum != "" {
result += "."
}
fmt.Println(fMap[n])
if n != 0 {
result += fmt.Sprintf("%s(%s)", floatNum[:fMap[n]-1], floatNum[fMap[n]-1:])
} else {
Expand Down

0 comments on commit 2b983c8

Please sign in to comment.