Home > front end >  kotlin product of odd or even integers
kotlin product of odd or even integers

Time:02-16

The problem I'm working on accepts a number string and will output the product of the odd or even numbers in the string. While the product of purely number string is working fine, my code should also accept strings that is alphanumeric (ex: 67shdg8092) and output the product. I'm quite confused on how I should code the alphanumeric strings, because the code I have done uses toInt().

Here's my code:

fun myProd(Odd: Boolean, vararg data: Char): Int {
    var bool = isOdd
    var EvenProd = 1
    var OddProd = 1
    for (a in data) 
    {
      val intVal = a.toString().toInt()
      if (intVal == 0) 
      {
        continue
      }
      if (intVal % 2 == 0)
      {
        EvenProd *= intVal
      }
      else 
      {
        OddProd *= intVal
      }
    }
    if(bool == true) return OddProd
    else return EvenProd
}

CodePudding user response:

Use toIntOrNull instead of toInt. It only converts numeric string

val intVal = a.toString().toIntOrNull()
if (intVal == null || intVal == 0) {
    continue
}

Starting from Kotlin 1.6 you can also use a.digitToIntOrNull().

P.S. Your method could be also rewritten in functional style

fun myProd(isOdd: Boolean, input: String): Int {
    return input.asSequence()
        .mapNotNull { it.toString().toIntOrNull() } // parse to numeric, ignore non-numeric
        .filter { it > 0 } // avoid multiplying by zero
        .filter { if (isOdd) it % 2 != 0 else it % 2 == 0 } // pick either odd or even numbers
        .fold(1) { prod, i -> prod * i }  // accumulate with initial 1
}
  • Related