mahmoud deif
mahmoud deif

Reputation: 27

Calculate the numbers without separating them

I can't solve this problem, how to separate the numbers and do the required arithmetic

https://codeforces.com/group/MWSDmqGsZm/contest/219158/problem/O

This is my code , I don't know how true it is

fun main(args:Array<String>) {

val scanner = Scanner(System.`in`)


var s: String = read()!!
var c: Char? = null
var a: String = ""
var b: String = ""
var t: Boolean = true
for (i in 1..s.length) {
    if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') {
        c = s[i]
        t = false
    }else{
        if(t){
            a+=s[i]
        }else{
            b+=s[i]
        }
    }
}

if(c=='+'){
    println(a+b)
}else if (c=='-'){
    println( "$a - $b" )
}else if (c=='*'){
    println("$a * $b")
}else{
    println("$a / $b")
}

Upvotes: 0

Views: 39

Answers (1)

Arpit Shukla
Arpit Shukla

Reputation: 10493

Try this code:

fun main() {
    val str = readLine()!!
    val (index, operator) = str.findAnyOf(listOf("+", "-", "*", "/"))!!
    val a = str.substring(0, index).toInt()
    val b = str.substring(index + 1).toInt()
    val result = when (operator) {
        "+" -> a + b
        "-" -> a - b
        "*" -> a * b
        "/" -> a / b
        else -> -1
    }
    println(result)
}

findAnyOf documentation:

Finds the first occurrence of any of the specified [strings] in this char sequence.
Returns A pair of an index of the first occurrence of matched string from [strings] and the string matched or null if none of [strings] are found.

Rest of the logic is quite straightforward.

Upvotes: 1

Related Questions