赞
踩
题目:请用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")
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。