1.배운내용
1)알고리즘 코드카타

문제를 모르겠어서 반복문 for문 조금 하다가 말았다.
코드
class Solution {
fun solution(num: Int): Int {
var answer = 0
for(0...n)
return answer
}
}
정답
class Solution {
fun solution(num: Int): Int = collatzAlgorithm(num.toLong(),0)
tailrec fun collatzAlgorithm(n:Long, c:Int):Int =
when{
c > 500 -> -1
n == 1L -> c
else -> collatzAlgorithm(if( n%2 == 0L ) n/2 else (n*3)+1, c+1)
}
}
lass Solution {
fun solution(num: Int): Int {
return processor(num.toLong(), 0)
}
private fun processor(n: Long, c: Int): Int {
if (n == 1.toLong()) {
return c
} else if (c == 500) {
return -1
}
return processor(if (n % 2.toLong() == 0.toLong()) n / 2 else n * 3 + 1, c + 1)
}
}
class Solution {
fun solution(num: Int): Int {
var processCount = 0
var currentNumber = num
while(processCount < 500) {
if(currentNumber == 1) return processCount
when(currentNumber % 2) {
0 -> currentNumber /= 2
1 -> {
currentNumber *= 3
currentNumber++
}
else -> return -1
}
processCount++
}
return -1
}
}
import java.math.BigInteger
class Solution {
fun solution(num: Int): Int {
return collatzCalc(num.toBigInteger(), 0)
}
fun collatzCalc(num: BigInteger, count: Int): Int {
val zero = BigInteger.ZERO
val one = BigInteger.ONE
val two = BigInteger.TWO
val tree = one + two
if (num == one) return count
if (count >= 500) return -1
return when(num%two == zero) {
true -> collatzCalc(num/two, count+1)
false -> collatzCalc(num * tree + one, count+1)
}
}
}
구글 검색해서 문제에 대해 알아 보았다.
이해
1. 짝수라면 2로 나눔
2. 홀수라면 3을 곱하고 1 더함
3. 같은 작업을 1이될때까지 반복
접근
- 1이 될때까지 분기 나눠주기
- count 500 되는 순간 return
풀이
class Solution {
fun solution(num: Int): Int {
var longNum = num.toLong()
var count = 0
while (count < 500 && longNum > 1) {
count ++
longNum = if (longNum % 2 == 0L) longNum / 2 else longNum * 3 + 1
}
return if (count == 500) -1 else count
}
}
주어진 문제는 숫자가 짝수일 경우 2로 나누고, 홀수일 경우 3을 곱한 후 1을 더하는 과정을 반복하여 숫자가 1이 될 때까지의 과정을 구현하는 것이다.
• 이 과정은 최대 500번까지만 반복하며, 그 이상 반복해도 1이 되지 않는 경우에는 -1을 반환한다.
• 이 문제의 함정은 입력값이 Int형이지만, 과정을 거치면서 결과값이 Int의 범위를 벗어날 수 있다는 점이다.
• 따라서, 결과값을 저장할 변수는 Long형으로 선언해야 한다.
....위의 글은 블로그에서 가져온 글이다.. Int 범위가 벗어나 Long은 알겠는데... 머리속이 뱅글뱅글...
2) 과제 시도
... 에러들이 났고, 수정을 시도하였다.
'개발일지' 카테고리의 다른 글
| 2024.01. 08 TIL (1) | 2024.01.08 |
|---|---|
| 2024.1.5 TIL (1) | 2024.01.05 |
| 20204.1.3 TIL (0) | 2024.01.03 |
| 2024.01.02 TIL (0) | 2024.01.02 |
| 23023.12.29 TIL (0) | 2023.12.29 |