kotlin字符串与数字数字与字符串转换
fun stringToInt(){
var a=3
var b="3"
a=b.toInt()
b=a.toString()
}
kotlin递归之阶乘
fun factorials(numbers:Int):Int{
//5的阶乘=5*4*3*2*1
//4的阶乘=4*3*2*1
//3的阶乘=3*2*1
//2的阶乘=2*1
//1的阶乘=1
//可以理解为5的阶乘等于5*4的阶乘
if(numbers==1){
return 1
}else{
return numbers*factorials(numbers-1)
}
}
当传入参数5时的结果
2020-08-21 14:16:09.412 7372-7372/com.example.myapplication I/kotlin: result=120
当传入参数100时的结果
2020-08-21 14:22:41.805 7945-7945/com.example.myapplication I/kotlin: result=0
出现这种情况的原因是因为函数的返回值Int取值范围在-2147483648~2147483647,而100的阶乘超过了这个范围,下面换成Long来测试
fun factorialsLong(numbers:Long):Long{
//5的阶乘=5*4*3*2*1
//4的阶乘=4*3*2*1
//3的阶乘=3*2*1
//2的阶乘=2*1
//1的阶乘=1
//可以理解为5的阶乘等于5*4的阶乘
if(numbers==1L){
return 1L
}else{
return numbers*factorialsLong((numbers-1))
}
}
2020-08-21 14:22:41.805 7945-7945/com.example.myapplication I/kotlin: result=0
此时Long类型也无法装在下100的阶乘,可以用BigInteger来装载
fun factorialsBigInteger(numbers:BigInteger):BigInteger{
//5的阶乘=5*4*3*2*1
//4的阶乘=4*3*2*1
//3的阶乘=3*2*1
//2的阶乘=2*1
//1的阶乘=1
//可以理解为5的阶乘等于5*4的阶乘
if(numbers== BigInteger.ONE){
return BigInteger.ONE
}else{
return numbers*factorialsBigInteger((numbers-BigInteger.ONE))
}
}
此时得到结果完美perfect
2020-08-21 14:36:56.635 10121-10121/com.example.myapplication I/kotlin: result=93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
网友评论