String
원하는 형식으로 String을 formatting하는 방법(추후 추가 예정)
String.format("%.4f",0.998999)
String.format("%d",30)
Substring을 추출하는 방법
//07:05:45PM
time_str = (s.substring(0,2).toInt()+12).toString() + s.substring(2,8) //19:05:45
sort
배열을 정열함
val new = arr.sorted() // var 변수는 sort 를 지원 않함.
new.sort() //ok
Array
초기값이 0인 N 개 배열 생성
var arr = Array<Int>(N) { i->0 } //0은 초기값
for
범위 순환
for(i in 0..10){
//TODO
}
for (i in 0 until N){
//TODO i max N -1?
}
for(i in list){
//TODO
}
bit 연산자
shl, shr
//flip
for(i in 0..31){
if((n and (number shl i))==zero){
templet+= (number shl i)
}
}
List
mutableListOf, remove, add 사용법(python에서의 list처럼 사용)
//pair number가 몇 셋트 있는지 구하는 문제
fun sockMerchant(ar: Array<Int>): Int {
// Write your code here
var nums = mutableListOf<Int>()
var pair: Int =0
var found : Int =0
for(i in ar){
found=0
if(nums.count()>0){
for(j in nums){
if(i==j){
pair+=1
nums.remove(j)
found =1
break
}
}
}
if(found==0){
nums.add(i)
}
}
return pair
}
!! 연산자
null값이 아니라는 것을 보증하는 연산자
readLine()!!.split(' ').forEach { str ->
if (mMap.containsKey(str) && mMap[str]!! > 1) {
mMap.put(str, mMap[str]!! - 1)
} else if (mMap.containsKey(str)) {
mMap.remove(str)
} else {
printYes = false
return@forEach
}
}
HashMap 사용
입력 받은 문자열에 대하여 중복단어 체크 및 HashMap에 넣는 코드
val mMap = HashMap<String, Int>()
readLine()!!.split(' ').forEach { str ->
if (mMap.containsKey(str)) {
mMap.put(str, mMap[str]!! + 1)
} else {
mMap.put(str, 1)
}
}
'Kotlin' 카테고리의 다른 글
[kotlin] Serialization을 이용하여 JSON를 다루어 보자 (0) | 2022.01.20 |
---|---|
[Kotlin] foreach 와 map 알고 쓰자 (0) | 2022.01.12 |
[kotlin] Collection & Sequence (0) | 2021.11.23 |
[Kotlin] apply, with, let, also, run 사용 (0) | 2021.11.09 |
Comment