題目描述:
Write a code fragment that puts the binary representation of a positive integer N into a String s
-
書(shū)中提示的 Java 寫(xiě)法
int N = 12345; String s = ""; for (int n = N; n > 0; n/=2) s = (n %2) + s
-
Kotlin 寫(xiě)法
才發(fā)現(xiàn) Kotlin 好像不論怎么寫(xiě)谆焊,都沒(méi)有辦法寫(xiě)出來(lái) for loop 可以在括號(hào)內(nèi)修改下一次迭代的值奴曙,用其它曲線(xiàn)救國(guó)的方式寫(xiě)也行,但是代碼很難看歌逢,所以,沒(méi)辦法屠阻,當(dāng)然是選擇
原諒它用遞歸啦fun main(args: Array<String>) { println(12345.toBinaryString()) //用Java自帶的函數(shù)驗(yàn)證一下 println(Integer.toBinaryString(12345)) } fun Int.toBinaryString(): String = if (this == 1) "1" else (this/2).toBinaryString() + this % 2
運(yùn)行結(jié)果:沒(méi)有問(wèn)題