我想对Long
变量的数字求和并将其添加到它自己的变量中,我附带了下一个工作代码:
private fun Long.sumDigits(): Long {
var n = this
this.toString().forEach { n += it.toString().toLong() }
return n
}
用法:
assert(48.toLong() == 42.toLong().sumDigits())
我必须使用
it.toString()
才能使其正常工作,因此我进行了下一个测试,但没有得到它的结果:@Test
fun toLongEquality() {
println("'4' as Long = " + '4'.toLong())
println("\"4\" as Long = " + "4".toLong())
println("\"42\" as Long = " + "42".toLong())
assert('4'.toString().toLong() == 4.toLong())
}
输出:
'4' as Long = 52
"4" as Long = 4
"42" as Long = 42
使用
char.toString().toLong()
是个好习惯还是有更好的方法将char
转换为Long
?"4"
是否由char
表示?为什么它不等于char
表示形式?
最佳答案
从文档中:
class Char : Comparable (source) Represents a 16-bit Unicode character. On the JVM, non-nullable values of this type are represented as values of the primitive type char.
fun toLong(): Long
Returns the value of this character as a Long.
当您使用
'4' as Long
时,您实际上会获得字符'4'的Unicode(ASCII)代码
关于kotlin - 为什么将单个char和 “single char String”转换为long(.toLong())时不相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51582890/