Kotlin program to convert octal number to decimal number

Kotlin | Octal to Decimal Conversion: Here, we are going to learn how to convert a given octal number to its equivalent decimal number in Kotlin programming language? Submitted by IncludeHelp, on April 25, 2020

Kotlin - Convert octal number to decimal number

Given a number in octal number system format, we have to convert it into decimal number system format.

Example:

Input:
num = 344

Output:
228

Program to convert octal number to decimal number in Kotlin

package com.includehelp.basic

import java.util.*

//Main function Entry Point of Program
fun main(arg: Array<String>) {
    //Input Stream
    val sc = Scanner(System.`in`)

    //Input Octal Number
    println("Enter Octal Number  : ")
    var octalNumber: Int = sc.nextInt()

    var decimalNumber=0
    var i = 0
    var isCorrectOctal=true;


    val octalStr = octalNumber.toString();
    //Check Given no is valid Ocatal Number or not
    for(i in octalStr.indices){
       if (octalStr[i] !in '0'..'7' ){
           isCorrectOctal=false
       }
    }

    if(isCorrectOctal){
        //Convert Octal to Decimal
        while (octalNumber > 0) {
            val r= octalNumber % 10
            decimalNumber += (r * Math.pow(8.0,i.toDouble())).toInt()
            octalNumber /= 10
            i ++
        }

        //Print Decimal Number
        println("Decimal: $decimalNumber")
    }else{
        System.err.println("Invalid Octal Number !!")
    }
}

Output

Run 1:
Enter Octal Number  :
344
Decimal: 228
-------
Run 2:
Enter Octal Number  :
48
Invalid Octal Number !!
-------
Run 3:
Enter Octal Number  :
47
Decimal: 39

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.