[算法] 大数相加

看到个有意思的问题 “给定2个整数,这两个数大的连long类型都装不下,如何计算两数和”

实践了一下,可以用数组存放,数组的每个元素对应大整数的每一个数位

fun bigNumberSum(bigNumA:String, bigNumB:String){

val maxArrayLength =if (bigNumA.length > bigNumB.length) bigNumA.length +1  else bigNumB.length +1

    val a = IntArray(maxArrayLength)

//倒序放入数组

    for (iin 0 until bigNumA.length )

{

a[i] = bigNumA[bigNumA.length -1 - i] -'0'

    }

val b = IntArray(maxArrayLength)

for (iin 0 until bigNumB.length)

{

b[i] = bigNumB[bigNumB.length -1 - i] -'0'

    }

var result = IntArray(maxArrayLength)

for (iin 0 until maxArrayLength){

var tem = result[i]

tem += a[i]

tem += b[i]

if (tem >=10)

{

tem -=10

            result[i+1] =1

        }

result[i] = tem

}

var sb = StringBuilder()

var findFirst =false

    //再次逆序取出

    for ( iin result.size -1 downTo 0)

{

if (!findFirst){

if (result[i] ==0){

continue

            }

findFirst =true

        }

sb.append(result[i])

}

println(sb.toString())

}

你可能感兴趣的:([算法] 大数相加)