kotlin 二进制
We are given a decimal number and we will create a Kotlin program to convert decimal number to binary.
我们给了十进制数,我们将创建一个Kotlin程序将十进制数转换为二进制 。
To convert decimal number to binary, we will recursively divide the decimal number by 2 and save the remainder found till the decimal number vanquishes.
要将十进制数转换为二进制,我们将十进制数递归除以2,然后将找到的余数保存到十进制数消失。
Example:
例:
Input:
Decimal number = 12
Recursive division:
Number | Quotient | Remainder |
---|---|---|
12 | 6 | 0 |
6 | 3 | 0 |
3 | 1 | 1 |
1 | 0 | 1 |
数 | 商 | 余 |
---|---|---|
12 | 6 | 0 |
6 | 3 | 0 |
3 | 1个 | 1个 |
1个 | 0 | 1个 |
在Kotlin中将十进制转换为二进制的程序 (Program to convert decimal to binary in Kotlin)
package com.includehelp.basic
import java.util.*
/* function to convert given decimal number into Binary */
fun getBinaryNumber(decimalNumber: Int): String {
var decimalNumber = decimalNumber
val binaryStr = StringBuilder()
while (decimalNumber > 0) {
val r = decimalNumber % 2
decimalNumber /= 2
binaryStr.append(r)
}
return binaryStr.reverse().toString()
}
// Main Method Entry Point of Program
fun main(arg: Array<String>) {
val sc = Scanner(System.`in`)
println("Enter Decimal Number : ")
//Input Decimal Number
val decimalNumber: Int = sc.nextInt()
// Call function to Convert Decimal into binary
val binaryNumber = getBinaryNumber(decimalNumber)
// Print Binary Number
println("Binary Number : $binaryNumber")
}
Output
输出量
Run 1:
Enter Decimal Number :
15
Binary Number : 1111
-----
Run 2:
Enter Decimal Number :
12345
Binary Number : 11000000111001
----
Run 3:
Enter Decimal Number :
545654
Binary Number : 10000101001101110110
翻译自: https://www.includehelp.com/kotlin/convert-decimal-to-binary.aspx
kotlin 二进制