kotlin2个整数相除求小数值,比如用10除以1285
时间: 2024-03-23 15:37:18 浏览: 26
可以使用 Kotlin 中的浮点数类型将两个整数相除得到小数值,例如:
```kotlin
val result: Double = 10.0 / 1285.0
println(result)
```
输出结果为:
```
0.007782101167315176
```
其中 `10.0` 和 `1285.0` 都是浮点数,相除的结果也是浮点数,可以通过 `Double` 类型的变量来保存。
相关问题
Array<String>中按照字符串转为整数的大小排序,使用kotlin
同样可以使用Kotlin中的sortedWith方法和自定义比较器来实现按照字符串转为整数的大小排序。具体代码如下:
```
fun main() {
val arr = arrayOf("10", "2", "31", "45", "6", "7", "8", "9")
val sortedArr = arr.sortedWith(Comparator { s1, s2 ->
val i1 = s1.toInt()
val i2 = s2.toInt()
i1 - i2
})
println(sortedArr.contentToString())
}
```
输出结果为:[2, 6, 7, 8, 9, 10, 31, 45]
使用kotlin将整数转为16进制的数
以下是使用 Kotlin 实现的代码:
```kotlin
class Solution {
fun toHex(num: Int): String {
if (num == 0) {
return "0"
}
val hex = "0123456789abcdef"
var n = num.toLong()
if (n < 0) {
n += (1L shl 32)
}
var res = ""
while (n > 0) {
val digit = n % 16
res = hex[digit.toInt()] + res
n /= 16
}
return res
}
}
```
该算法使用了类似于转换为二进制数的方法将整数转换为十六进制数。我们首先处理特殊情况:如果输入的数为零,则返回 "0"。
然后,我们定义一个包含所有十六进制数字的字符串 `hex`,以及一个用于存储结果的字符串 `res`。我们将输入的整数转换为 `Long` 类型,并判断其是否为负数。如果是负数,则将其转换为补码表示。最后,我们从低位到高位遍历整数,将每一位转换为十六进制数字,并将其添加到结果字符串的开头。
该算法的时间复杂度为 O(logn),其中 n 是输入的整数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)