[Swift]LeetCode166. 分数到小数 | Fraction to Recurring Decimal

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

Example 1:

Input: numerator = 1, denominator = 2
Output: "0.5"

Example 2:

Input: numerator = 2, denominator = 1
Output: "2"

Example 3:

Input: numerator = 2, denominator = 3
Output: "0.(6)"


给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数。

如果小数部分为循环小数,则将循环的部分括在括号内。

示例 1:

输入: numerator = 1, denominator = 2
输出: "0.5"

示例 2:

输入: numerator = 2, denominator = 1
输出: "2"

示例 3:

输入: numerator = 2, denominator = 3
输出: "0.(6)"

8ms
 1 class Solution {
 2     func fractionToDecimal(_ numerator: Int, _ denominator: Int) -> String {
 3         let s1 = numerator > 0 ? 1 : -1
 4         let s2 = denominator > 0 ? 1 : -1
 5         let numerator = abs(numerator)
 6         let denominator = abs(denominator)
 7         let num = numerator / denominator
 8         var remain = numerator % denominator
 9         var remains = [Int : Int]()
10         var res = ""
11         if s1*s2 < 0 && (num > 0 || remain > 0) {
12             res += "-"
13         }
14         res += "\(num)"
15         if remain > 0 {
16             res += "."
17         }
18         var frac = ""
19         var pos = 0
20         while remain > 0 {
21             if let pos = remains[remain] {
22                 frac.insert("(", at: frac.index(frac.startIndex, offsetBy: pos))
23                 frac += ")"
24                 return res+frac
25             }
26             remains[remain] = pos
27             frac += String(remain*10 / denominator)
28             remain = remain*10 % denominator
29             pos += 1
30         }
31         return res+frac
32     }
33 }


12ms

 1 class Solution {
 2     func fractionToDecimal(_ numerator: Int, _ denominator: Int) -> String {
 3
 4         if denominator == 0 { return "NaN" }
 5
 6         //Big bad voodoo magic.
 7         var numerator = numerator
 8         var denominator = denominator
 9
10         //Note, for bools "!=" behaves the same as "^" which is not allowed.
11         var negative = (numerator < 0) != (denominator < 0)
12
13         numerator = abs(numerator)
14         denominator = abs(denominator)
15
16         var result = String(numerator / denominator)
17         var remainder = (numerator % denominator) * 10
18
19         if remainder == 0 {
20             if negative == true && numerator != 0 {
21                 return String("-") + result
22             } else {
23                 return result
24             }
25         }
26
27         result += "."
28
29         //See if we find repeating digits...
30         //At the point where our long division keeps
31         //dividing into the same NO, we loop 4evz
32         var repeatMap = [Int:Int]()
33
34         while remainder != 0 {
35
36             //We got a repeater? Or nah?
37             if let repeatIndex = repeatMap[remainder] {
38                 result.insert("(", at: result.index(result.startIndex, offsetBy: repeatIndex))
39                 result += ")"
40                 break
41             }
42
43             result += String(remainder / denominator)
44
45             //Set our repeater..
46             repeatMap[remainder] = result.count - 1
47
48             //Perform one more step of long division
49             remainder = (remainder % denominator) * 10
50         }
51
52         if negative == true {
53             return String("-") + result
54         }
55         return result
56     }
57 }


12ms

 1 class Solution {
 2     func fractionToDecimal(_ numerator: Int, _ denominator: Int) -> String {
 3
 4         if numerator  == 0 {
 5             return "0"
 6         }
 7
 8         var res = ""
 9
10         if ((numerator < 0) && (denominator >= 0)) || ((numerator >= 0) && (denominator < 0)) {
11             res += "-"
12         }
13
14         let absNum = abs(numerator)
15         let absDen = abs(denominator)
16
17         res += String(absNum/absDen)
18
19         var remander = absNum % absDen
20
21         if remander == 0 {
22             return res
23         }
24
25         res += "."
26
27         var remanders = [Int : Int]()
28
29         var pos = res.count
30
31         var add = 0
32         var hasRecycyle = false
33
34         while remander != 0 && !hasRecycyle {
35             if remanders.keys.contains(remander) {
36                 add = remanders[remander]!
37                 hasRecycyle = true
38                 continue
39             }
40
41             remanders[remander] = pos
42             pos += 1
43             res += String(10 * remander / absDen)
44             remander = (10 * remander) % absDen
45         }
46
47         if hasRecycyle {
48             res.insert("(", at: res.index(res.startIndex, offsetBy: add))
49             res += ")"
50         }
51
52
53         return res
54     }
55 }


16ms

 1 class Solution {
 2     func fractionToDecimal(_ numerator: Int, _ denominator: Int) -> String {
 3         var s1:Int = numerator >= 0 ? 1 : -1
 4         var s2:Int = denominator >= 0 ? 1 : -1
 5         var num:Int = abs(numerator )
 6         var den:Int = abs(denominator )
 7         var out:Int = num / den
 8         var rem:Int = num % den
 9         var m:[Int: Int] = [Int: Int]()
10         var res:String = String(out)
11         if s1 * s2 == -1 && (out > 0 || rem > 0)
12         {
13             res = "-" + res
14         }
15         if rem == 0 {return res}
16         res += "."
17         var s:String = ""
18         var pos:Int = 0
19         while(rem != 0)
20         {
21             if m[rem] != nil
22             {
23                 var index = s.index(s.startIndex, offsetBy: m[rem]!)
24                 s.insert("(", at:index )
25                 s += ")"
26                 return res + s
27             }
28             m[rem] = pos
29             s += String((rem * 10) / den)
30             rem = (rem * 10) % den
31             pos += 1
32         }
33         return res + s
34     }
35 }


20ms

 1 class Solution {
 2     func fractionToDecimal(_ numerator: Int, _ denominator: Int) -> String {
 3
 4         if numerator % denominator == 0 {
 5             return String(numerator/denominator)
 6         }
 7
 8         let n = abs(numerator);
 9         let d = abs(denominator);
10
11         var sign = ""
12
13         if numerator > 0 && denominator < 0 || numerator < 0 && denominator > 0{
14             sign = "-"
15         }
16
17         var i = n
18         while i > d {
19             i = i/d
20         }
21
22         var dic = Dictionary<Int, Int>()
23
24         var res = n % d;
25         var s = String()
26
27         var count = 0
28
29         repeat {
30             dic[res] = count
31             res = res * 10;
32             s.append(String(abs(res/d)))
33             res = res % d
34             count = count + 1
35         } while (res != 0 && dic[res] == nil)
36
37         if res == 0 {
38             return sign + String(n/d) + "." + s;
39         }
40         let idx = s.index(s.startIndex, offsetBy: dic[res]!)
41         return sign + String(n/d) + "." + s.substring(to: idx) + "(" + s.substring(from: idx) + ")"
42     }
43 }


20ms

 1 class Solution {
 2     func fractionToDecimal(_ numerator: Int, _ denominator: Int) -> String {
 3         let r = numerator % denominator
 4         let k = numerator / denominator
 5         if r == 0 {
 6             return "\(k)"
 7         }
 8
 9         let tail = helper(abs(r), abs(denominator))
10         var ret = "\(abs(k)).\(tail)"
11         if numerator * denominator < 0 {
12             ret = "-" + ret
13         }
14         return ret
15     }
16
17
18     func helper(_ n: Int, _ m: Int) -> String {
19         var ret = ""
20         var map = [Int: Int]()
21         var x = n
22         while x != 0 {
23             if let i = map[x] {
24                 ret = ret.prefix(i) + "(" + ret.suffix(ret.count - i) + ")"
25                 return ret
26             }
27             let y = x * 10
28             let k = y / m
29             map[x] = ret.count
30             ret += "\(k)"
31             x = y % m
32         }
33         return ret
34     }
35 }


36ms

 1 class Solution {
 2     func fractionToDecimal(_ numerator: Int, _ denominator: Int) -> String {
 3          if denominator == 0 {
 4             return ""
 5         }
 6
 7         if numerator == 0 {
 8             return "0"
 9         }
10
11         //取绝对值
12         var num1 = numerator > 0 ? numerator : -numerator
13         let num2 = denominator > 0 ? denominator : -denominator
14         //取方向
15         var  result = (numerator > 0 && denominator < 0) || (numerator < 0 && denominator > 0) ? "-" : ""
16
17         //整数部分
18         result += String(num1/num2)
19         num1 = num1 % num2
20         if num1 == 0 {
21             return result
22         }else {
23             result += "."
24         }
25
26         //小数部分
27         var dic = [Int:Int]()
28
29         while num1 != 0 {
30             if dic.keys.contains(num1) {
31                 let index = result.index(result.startIndex, offsetBy: dic[num1]!)
32                 result.insert("(", at: index)
33                 result += ")"
34                 break
35             }
36             dic[num1] = result.count
37             num1 *= 10
38             result += String(num1/num2)
39             num1 %= num2
40         }
41         return result
42     }
43 }


56ms

 1 class Solution {
 2     func fractionToDecimal(_ numerator: Int, _ denominator: Int) -> String {
 3         if numerator == 0 { return "0" }
 4         let sign = (numerator > 0 ? 1 : -1) ^ (denominator > 0 ? 1 : -1) == 0 ? "" : "-"
 5         var result = sign
 6         var a = abs(numerator)
 7         let b = abs(denominator)
 8         result += "\(a/b)"
 9         a = a % b
10         if a != 0 {
11             result += "."
12         } else {
13             return result
14         }
15         var decimal = ""
16         var array = [a]
17         while true {
18             a = a * 10
19             decimal += "\(a/b)"
20             a = a % b
21             if a == 0 {
22                 result += decimal
23                 return result
24             }
25             if let index = array.index(of: a) {
26                 var temp = [Character](decimal)
27                 temp.insert("(", at: index)
28                 temp.append(")")
29                 result += String(temp)
30                 return result
31             } else {
32                 array.append(a)
33             }
34         }
35     }
36 }

原文地址:https://www.cnblogs.com/strengthen/p/10127520.html

时间: 2024-08-27 05:26:24

[Swift]LeetCode166. 分数到小数 | Fraction to Recurring Decimal的相关文章

【LeetCode】Fraction to Recurring Decimal

Fraction to Recurring Decimal Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. For example, Given numera

LeetCode 166. Fraction to Recurring Decimal(模拟)

题目 题意:给出一个分数的分子和分母,给出这个分数的小数形式的字符串模式.循环的部分用( 括上. 题解:模拟除法,判断循环体. class Solution { public: map<int,int> m; string fractionToDecimal(int numerator, int denominator) { long long int numerator_ = numerator; long long int denominator_ = denominator; int s

[LeetCode]58. Fraction to Recurring Decimal分数化小数

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. For example, Given numerator = 1, denominator = 2, retu

166 Fraction to Recurring Decimal 分数到小数

给定两个整数,分别表示分数的分子和分母,返回字符串格式的小数.如果小数部分为循环小数,则将重复部分括在括号内.例如,    给出 分子 = 1, 分母 = 2,返回 "0.5".    给出 分子 = 2, 分母 = 1,返回 "2".    给出 分子 = 2, 分母 = 3,返回 "0.(6)". 详见:https://leetcode.com/problems/fraction-to-recurring-decimal/descriptio

[LeetCode] Fraction to Recurring Decimal 分数转循环小数

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. For example, Given numerator = 1, denominator = 2, retu

[LeetCode] 167. Fraction to Recurring Decimal 分数转循环小数

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. Example 1: Input: numerator = 1, denominator = 2 Output

leetcode166. Fraction to Recurring Decimal

题意:给出分子和分母,用字符串表示结果,循环的部分用“()”括起来. 思路: 模拟笔算, 最初根据1/99的情况,设想用path记录余数相同时的间隔步长,但只能用于处理(00..0n)的情况,其中n为[1,9]: 后来采取网上看到用map记录<余数,出现位置>的想法. 通过判断map中key是否重复来判断是否循环,通过key对应的出现位置,来判断循环位数. 列表记录商. 注意: 被除数为0的情况: 被除数为min_int的情况:(用long处理) 结果为负数的情况: 只有正数的情况. 代码:

[LeetCode]Fraction to Recurring Decimal

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. For example, Given numerator = 1, denominator = 2, retu

Fraction to Recurring Decimal

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. For example, Given numerator = 1, denominator = 2, retu