【面试题库】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()
    }
}

单元测试用例

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")
    }
}

你可能感兴趣的:(kotlin,开发语言,android)