集合正序输出
var nums = 1 .. 100 //[1]
for (num in nums){
输出的num分别是1,2,3,4,5.....到一百
LogUtils.i("num-->${num}" ,"数字")
}
//--------------------------------------------------
集合跳过
var num2 = 1 until 16 //until代表[1,16)闭区间1到15 []闭区间算第一位最后一位()开区间不包含第一位和最后一位
for (mString in num2 step 3){//step步长 步长是3 输出的结果是1,4,7,10,13,步长是2,输出结果是1,3,5,7,9,11,13,15
LogUtils.i("num-->${mString}" ,"数字")
}
//---------------------------------------------------
集合倒序输出
var num2 = 1 until 16
var num3 = num2.reversed()
//reversed反转
for (numReversed in num3){
LogUtils.i("num-->${numReversed}" ,"数字反转")
}
//------------------------------------------------------
kotlin 递归
BigInteger代表很大很大的数
var num = BigInteger("100");
LogUtils.i("阶乘总和","${fact(num)}")
fun fact(num:BigInteger):BigInteger{
if(num==BigInteger.ONE){
return BigInteger.ONE
}else{
return num*fact(num- BigInteger.ONE )
}
}
//---------------------------------------------------累加
5的累计 5+4+3+2+1
LogUtils.i("5的累加:","${ollAdd(5)}")
fun ollAdd(number: Int):Int{
if(number==1){
return 1;
}else{
return number + ollAdd(number-1)
}
}
//--------------------------------------------------------
尾递归优化
var result = 0;
LogUtils.i("5的累加:","${ollAdd(100,result)}")
}
tailrec fun ollAdd(number: Int,result:Int):Int{
LogUtils.i("计算机第","${number}次计算,result=${result}")
if(number==0){
return 1;
}else{
return ollAdd(number-1,result+number)
}
}
//-----------------------------------------------------------
list
var lists= listOf("哈哈","呵呵","嘿嘿","嘻嘻","噗")
for ((i,e) in lists.withIndex()){
print("$i $e")
LogUtils.i("高兴就要","${e}")
}