개발일지

20204.1.3 TIL

과일바구니♡ 2024. 1. 3. 21:05

1. 배운내용

  1) 알고리즘 코드카타

     두정수사이의 합

      문제 설명

두 정수 a, b가 주어졌을 때 a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수, solution을 완성하세요. 
예를 들어 a = 3, b = 5인 경우, 3 + 4 + 5 = 12이므로 12를 리턴합니다.

 

초기코드

class Solution {
    fun solution(a: Int, b: Int): Long {
        var answer: Long = 0
        return answer
    }
}

 

 

생각

sum은 들어가겠다.

반복문이 쓰일까?

 

long= sum(a+b) return answer.  에러내고 정답 봄.

 

정답들

class Solution {
    fun solution(a: Int, b: Int): Long {
        var answer = 0L

        if(a > b) {
            for(n in b.. a) {
                answer += n
            }
        } else {
            for(n in a.. b) {
                answer += n
            }
        }
        return answer
    }
}

 

class Solution {
    fun solution(a: Int, b: Int): Long {
        val start : Long = (if(a>b) b else a).toLong()
        val end : Long = (if(a>b) a else b).toLong()
        return (start..end).sum()
    }
}

 

class Solution {
    fun solution(a: Int, b: Int): Long {
        var answer = 0L

        if (a == b){
            return a.toLong()
        }

        var min = Integer.min(a,b)
        var max = Integer.max(a,b)

        for (i in min .. max){
            answer += i
        }

        return answer
    }
}
class Solution {
    fun solution(a: Int, b: Int): Long {
       var answer = 0L

       val numList = if(a < b)
        (a.toLong()..b.toLong())
        else 
        (b.toLong()..a.toLong())

       answer = numList.sum()
       return answer
    }
}

 

 모르겠다. 문제를 구글링을 했다.

블로그들에서 나온 글들이다.

 

의식의 흐름

1. for문 돌리면 되는데 리턴값이 Long이다. 왜? 합은 Int Range보다 더 커질수 있어서 그런 듯 하다

2. a와 b의 대소관계가 정해져 있지 않으므로 import kotlin.math.* 하면 min()과 max()를 쓸 수 있어 간단해질 것 같다

해결 코드 

import kotlin.math.*

class Solution { fun solution(a: Int, b: Int) =(

min(a, b)..max(a, b)).fold(0L) {

total, next -> total + next }.toLong() }

 

a,b가 같아도 돌아가니까 이렇게 위 코드로 했는데 일부가 자꾸 틀림!!! 아니?? 도대체 왜????? ㅠㅠㅠ

는 바로 fold의 초기값이 0이기 때문이다. 오...

저걸 0L으로 바꾸니까 성공했다. 더하다가 Int Range를 벗어난거였음 ^^)/ 편-안

 

이해

a ~ b 모든 정수의 합 return

접근

  1. answer = 0L
  2. a < b
    1. a..b
  3. a > b
    1. a downTo b

풀이

class Solution {
    fun solution(a: Int, b: Int): Long {
        //정답을 Int -> Long 으로 변환하면 오류 난다. 처음부터 Long으로 선언
        var answer = 0L
        if (a < b) {
            for (i in a..b) {
                answer += i
            }
        } else {
            for (i in a downTo b) {
                answer += i
            }
        }
        return answer
    }
}

 

1. a와 b의 대소 비교를 해서 반복문을 통해 정수사이의 합을 구합니다. 

class Solution {
    fun solution(a: Int, b: Int): Long {
        return if(a<=b) (a..b).map{it.toLong()}.sum() else (b..a).map{it.toLong()}.sum()
    }
}

 

두 정수를 a와 b라고 했을 때 a가 b보다 작거나 같은 경우 a부터 b까지 차례대로 더하고 리턴
a가 b보다 클 경우 b부터 a까지 차례대로 더하고 리턴

 

fun solution(a: Int, b: Int): Long {

    return when (a <= b) {
        true -> (a..b).fold(0L, {total, next -> total + next})
        else -> (b..a).fold(0L, {total, next -> total + next})
    }
}

 

Math.abs()

Math.abs()함수는 숫자의 절대값을 반환합니다 .

 

fold

public inline fun <T, R> Iterable<T>.fold(
    initial: R,
    operation: (R, T) -> R
): R

fold의 초기값은 파라미터를 통해 자유롭게 정할 수 있으며, 반환 값은 초기값의 자료형이 되는 것을 알 수 있습니다

 

참고사이트 https://velog.io/@blucky8649/코틀린-reduce-fold-함수

............

 

2)강의 듣기, 과제 시도하기

 과제를 조금 시도했다. 그리고 sql 관련된 영상들을 보았다.

'개발일지' 카테고리의 다른 글

2024.1.5 TIL  (1) 2024.01.05
2024.1.4 TIL  (0) 2024.01.04
2024.01.02 TIL  (0) 2024.01.02
23023.12.29 TIL  (0) 2023.12.29
2023.12.28 TIL  (0) 2023.12.28