Given an integer,return its base 7 string representation.
Example 1:
input: 100Output: "202"
Example 2:
input: -7Output: "-10"
Note: The input will be in range of [-1e7,1e7].
给定一个整数,将其转化为7进制,并以字符串形式输出。
示例 1:
输入: 100输出: "202"
示例 2:
输入: -7输出: "-10"
注意: 输入范围是 [-1e7,1e7] 。
16ms
1 class Solution { 2 func convertToBase7(_ num: Int) -> String { 3 if num == 0 {return "0"} 4 var res:[Int] = [Int]() 5 //取绝对值 6 var number:Int = abs(num) 7 while(number != 0) 8 { 9 var temp:Int = number % 710 number /= 711 //在位置0处插入12 res.insert(temp,at: 0)13 }14 //数组转字符串15 let dataInt = res.map(String.init) 16 var str:String = dataInt.joined(separator: "")17 if num < 018 {19 str = "-" + str20 }21 return str22 }23 }
8ms
1 class Solution { 2 func convertToBase7(_ num: Int) -> String { 3 var input = abs(num) 4 5 var result = "" 6 7 if num == 0 { 8 return "0" 9 }10 11 while input >= 1 {12 result = "\(input % 7)" + result13 input = input / 714 }15 16 if num < 0 {17 result = "-" + result18 }19 20 return result21 }22 }
12ms
1 class Solution { 2 func convertToBase7(_ num: Int) -> String { 3 if num == 0 { return "0" } 4 let number = abs(num) 5 var result = "" 6 var x = number 7 while x > 0 { 8 let rem = x % 7 9 result = "\(rem)\(result)"10 x = x / 711 }12 13 return num < 0 ? "-\(result)" : result14 }15 }
20ms
1 class Solution { 2 func convertToBase7(_ num: Int) -> String { 3 if num < 0 { 4 return "-" + convertToBase7(-num) 5 } 6 7 var res = "" 8 var num = num 9 10 while num >= 7 {11 res = String(num % 7) + res12 num /= 713 }14 res = String(num) + res15 16 return res17 }18 }
24ms
1 class Solution { 2 func convertToBase7(_ num: Int) -> String { 3 guard num != 0 else { 4 return "0" 5 } 6 var num = num 7 var flag = true 8 if num < 0 { 9 flag = false10 num = -num11 }12 var result = ""13 while num > 0 {14 result = "\(num % 7)" + result15 num = num / 716 }17 return flag ? result : ("-" + result)18 }19 }总结
以上是内存溢出为你收集整理的[Swift]LeetCode504. 七进制数 | Base 7全部内容,希望文章能够帮你解决[Swift]LeetCode504. 七进制数 | Base 7所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)