• 白乾涛
    2022-03-05
    老师好,我对方法二又做了一些修改,主要是将一堆临时方法去掉了,老师帮忙看看这种思维合不合适 fun fractionAddition(expression: String): String { var lcm: Int // 分母的最小公倍数 val addValue = expression.replace("-", "+-") // 分子加减运算的结果 .split("+") .filter { it.trim() != "" } .map { Expression(it) } // 将 String 集合转换为 Expression 集合 .also { list -> lcm = list.map { it.denominator }.reduce(::lcm) } // 最小公倍数 ① .map { it.numerator * lcm / it.denominator } // 分子通分 .reduce { a, b -> a + b } //将所有的分子相加 val gcd = gcd(abs(addValue), lcm) // 分子和分母的最大公约数 println("$lcm $addValue $gcd") return "${addValue / gcd}/${lcm / gcd}" // 简化分数 } data class Expression(val exp: String, var numerator: Int = 0, var denominator: Int = 1) { init { exp.trim() .split("/") .takeIf { it.size == 2 } ?.let { numerator = it[0].toInt(); denominator = it[1].toInt() } } }
    展开

    作者回复: 很妙,init代码段用的挺好~ PS:作为算法题解很好,生产环境还是不推荐这么写数据类哈。

    
    1
  • 白乾涛
    2022-03-03
    感觉用kotlin刷题意义不大,因为kotlin新增的那么多语法、特性,以及协程,都用不上,这样子的kotlin没啥优势

    作者回复: 当我们必须刷题的时候,我会更喜欢Kotlin,而不是Java,它能帮我们熟悉Kotlin的基础语法、集合API,其实这就够了。 其实,你说的也很对,要灵活运用Kotlin的特性,刷题是不够的,刷题只能打基础。丰富的语言特性,只能去实战项目当中去运用。

    
    1
  • jim
    2022-02-07
    朱涛老师,这个系列可以单独开一个课程,非常期待

    作者回复: 感谢你的认可,将来有机会的话,我会考虑写点相关的博客出来的。

    
    1
  • Geek_473933
    2023-01-16 来自福建
    fun fractionAddition(expression: String): String { var lcm: Int return expression .replace("-", "+-") .split("+") .filter { it.isNotBlank() } .map { it.split("/").let { list -> list[0].toInt() to list[1].toInt() } }.also { list -> lcm = list.map { it.second }.reduce(::lcm) }.sumOf { it.first * lcm / it.second }.let { val gcd = gcd(abs(it), lcm) val pair = it / gcd to lcm / gcd "${pair.first}/${pair.second}" } } //最小公倍数 fun lcm(x: Int, y: Int): Int = x * y / gcd(x, y) //最大公约数 fun gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)
    
    
  • 春夏秋冬
    2022-11-05 来自北京
    class Solution { fun fractionAddition(expression: String): String = expression.replace("-", "+-") .split("+").filter { it.isNotEmpty() } .map(this::toPair) .fold(Pair(0, 1), this::sum) .string() private fun toPair(expr: String): Pair<Int, Int> = expr.split("/").let { Pair(it[0].toInt(), it[1].toInt()) } private fun sum(a: Pair<Int, Int>, b: Pair<Int, Int>): Pair<Int,Int> = lsm(a.second, b.second).let { Pair( it/a.second * a.first + it/b.second * b.first, it ) }.small() private fun gcd(a: Int, b: Int): Int = if (a % b == 0) b else gcd(b, a % b) private fun lsm(a: Int, b: Int): Int = a * b /gcd(a, b) private fun Pair<Int, Int>.small() = gcd(this.first, this.second).let { val abs = abs(it) Pair(this.first / abs, this.second / abs) } private fun Pair<Int, Int>.string() = "${this.first}/${this.second}" }
    展开
    
    