在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given two strings In general a rational number can be represented using up to three parts: an integer part, a non-repeating part,and a repeating part. The number will be represented in one of the following three ways:
The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example: 1 / 6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66) Both 0.1(6) or 0.1666(6) or 0.166(66) are correct representations of 1 / 6.
Example 1: Input: S = true
Explanation:
Because "0.(52)" represents 0.52525252..., and "0.5(25)" represents 0.52525252525..... , the strings represent the same number.
Example 2: Input: S = true
Example 3: Input: S = true
Explanation:
"0.9(9)" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.]
"1." represents the number 1, which is formed correctly: (IntegerPart) = "1" and (NonRepeatingPart) = "".
Note:
给定两个字符串 通常,有理数最多可以用三个部分来表示:整数部分
十进制展开的重复部分通常在一对圆括号内表示。例如: 1 / 6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66) 0.1(6) 或 0.1666(6) 或 0.166(66) 都是 1 / 6 的正确表示形式。 示例 1: 输入:S = "0.(52)", T = "0.5(25)" 输出:true 解释:因为 "0.(52)" 代表 0.52525252...,而 "0.5(25)" 代表 0.52525252525.....,则这两个字符串表示相同的数字。 示例 2: 输入:S = "0.1666(6)", T = "0.166(66)" 输出:true 示例 3: 输入:S = "0.9(9)", T = "1." 输出:true 解释: "0.9(9)" 代表 0.999999999... 永远重复,等于 1 。[有关说明,请参阅此链接] "1." 表示数字 1,其格式正确:(IntegerPart) = "1" 且 (NonRepeatingPart) = "" 。 提示:
8ms 1 class Solution { 2 func isRationalEqual(_ S: String, _ T: String) -> Bool { 3 return abs(convertToDouble(S) - convertToDouble(T)) < 1e-8 4 } 5 6 func convertToDouble(_ S: String) -> Double 7 { 8 var index = S.firstIndex(of: "(") ?? S.endIndex 9 if index == S.endIndex 10 { 11 return Double(S)! 12 } 13 else 14 { 15 var sb:String = String(S[..<index]) 16 let rightIndex = S.firstIndex(of: ")") ?? S.startIndex 17 if rightIndex != S.startIndex 18 { 19 index = S.index(after: index) 20 var rep:String = String(S[index..<rightIndex]) 21 while(sb.count < 50) 22 { 23 sb += rep 24 } 25 } 26 return Double(sb)! 27 } 28 } 29 } 12ms 1 class Solution { 2 func isRationalEqual(_ S: String, _ T: String) -> Bool { 3 if abs(parse(str: S) - parse(str: T)) < 0.0000001 { 4 return true 5 } 6 return false 7 } 8 func parse(str: String) -> Double { 9 if let dotIndex = str.firstIndex(of: "(") { 10 let ddIndex = str.firstIndex(of: ".") 11 var ans: Double = 0 12 ans += Double(String(str[str.startIndex..<dotIndex]))! 13 var dotStr = String(str[dotIndex..<str.endIndex]).dropFirst().dropLast() 14 let nn = dotIndex.encodedOffset - ddIndex!.encodedOffset + dotStr.count - 1 15 for i in 0...10 { 16 ans += Double(dotStr)! * pow(10.0, -Double(nn+i*(dotStr.count))) 17 } 18 return ans 19 } else { 20 return Double(str)! 21 } 22 } 23 }
|
请发表评论