当前位置:   article > 正文

【面试题库】Kotlin 手写大数计算器-加法

【面试题库】Kotlin 手写大数计算器-加法

题目:请用Kotlin手写一个大数计算器,附单元测试用例

package com.test.jetpack.calculator.v3

class BigStringAdd {
    fun addStringSum(leftStr: String, rightStr: String): String {
        var leftIndex = leftStr.length - 1
        var rightIndex = rightStr.length - 1
        var carry = 0
        val sb = StringBuilder()

        while (leftIndex >= 0 || rightIndex >= 0) {
            val leftVal = if (leftIndex >= 0) leftStr[leftIndex].digitToInt() else 0
            val rightVal = if(rightIndex>=0) rightStr[rightIndex].digitToInt() else 0
            val curSum = leftVal + rightVal + carry
            print("leftIndex:$leftIndex,rightVal:$rightVal,leftVal$leftVal,rightVal:$rightVal,curSum:$curSum,str:${curSum%10},carry:${curSum/10}")
            print("\n")
            sb.append(curSum % 10)
            carry = (curSum / 10)
            leftIndex--
            rightIndex--
        }
        if(carry>0) sb.append(carry)
        return sb.reverse().toString()
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

单元测试用例

import com.heancoder.jetpack.calculator.v3.BigStringAdd
import kotlin.test.Test
import kotlin.test.assertEquals

class TestCalculator {
    @Test
    fun testCalculator(){
        val ba = BigStringAdd()
        val sum = ba.addStringSum("999","1")
        assertEquals(sum,"1000")
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号