sean.jin
Spark Code Blog
sean.jin
전체 방문자
오늘
어제
  • 분류 전체보기
    • 개발공부
      • Kotlin
      • LeetCode
      • Algorithm
      • React
    • 주식차트
    • 책리뷰
    • 유틸리티

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 주식책리뷰
  • 네마녀의날
  • 쿼드러플위칭데이
  • 주식투자
  • 변동성
  • 초보
  • 부의 추월차선
  • 자기개발
  • 책
  • 트리플 위칭데이
  • 책리뷰
  • 주식입문자
  • 오
  • 경제
  • 책추천
  • 아빠와 딸의 주식투자 레슨

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
sean.jin

Spark Code Blog

[Kotlin]  LeetCode: PlusOne 쉬운 풀이 해설
개발공부/LeetCode

[Kotlin] LeetCode: PlusOne 쉬운 풀이 해설

2021. 6. 14. 16:09
반응형
문제

Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

 

array안에는 음의 정수가 없고 각 array의 숫자들은 digit을 나타냅니다.  맨앞자리에는 0 이 올수없습니다. 그리고 이 수에 1을 더한 값을 리턴하는게 이 문제의 목표입니다. 

 

예시

풀이
//digits = [1,2,3,9]
class Solution {
    fun plusOne(digits: IntArray): IntArray {
    if (digits.last() < 9) { //digit array에서 마지막 숫자를 찾습니다. 
    						//digits.last() = 9 이기때문에 for로 넘어가게됩니다.
        digits[digits.lastIndex] = digits.last() + 1 //9보다 작은수라면 마지막자리에 위치하는 array에 +1을 합니다.
        return digits //답
    }
    
    //여기는 1의 자리 숫자가 9일때 실행됩니다.
    for (i in digits.lastIndex downTo 0) { //거꾸로 0까지 반복
        digits[i]++ // 거꾸로 반복하기때문에 1의자리부터 1씩 더해집니다.
        if (digits[i] >= 10) { //만약 10이라면 다음 자릿수에 올림을 해야하기때문에 다음자리수로 이동하여 다시 1을 더합니다.
            digits[i] = 0//9에서 1을더해서 10이됬을때는 0을 만듭니다. 
        } else {
            return digits //만약 10이 아닌 숫자가 나왔다면 종료하고 digits array를 반환합니다.
        }
    }
    return intArrayOf(1, *digits)
}
}
과정 코드위치 | 풀이
[1, 2, 3, 9] if | intarray digit을 받습니다. intarray에 마지막 자리가 9임을 확인했습니다. 
[1, 2, 3, 9 + 1] for | 그래서 for Loop에가서 digits[i]++ 1을 더합니다.
[1, 2, 3, 10] for | 10은 0으로 바꾸고 for loop로 다음자리수에 1을더합니다.
[1, 2, 3+1, 0] for | 3에 1이 더해진다. 
[1, 2, 4, 0] 답
반응형

'개발공부 > LeetCode' 카테고리의 다른 글

[Kotlin] map, hashmap 같은지 비교하기 LeetCode: Valid Anagram  (0) 2021.06.22
[Kotlin] String에서 반복되지않은 char찾기 - LeetCode: First Unique Character in a String  (0) 2021.06.20
[Kotlin] LeetCode: Intersection of Two Arrays IISolution 풀이  (0) 2021.06.11
[Kotlin] Array 에 같은 숫자 찾기, HashMap활용 풀이 - LeetCode: Single Number  (0) 2021.06.10
[Kotlin] Array에 반복되는 아이템 삭제하기 - ArrayList distinct - LeetCode: Contains Duplicate - 풀이 과정  (0) 2021.06.08
    '개발공부/LeetCode' 카테고리의 다른 글
    • [Kotlin] map, hashmap 같은지 비교하기 LeetCode: Valid Anagram
    • [Kotlin] String에서 반복되지않은 char찾기 - LeetCode: First Unique Character in a String
    • [Kotlin] LeetCode: Intersection of Two Arrays IISolution 풀이
    • [Kotlin] Array 에 같은 숫자 찾기, HashMap활용 풀이 - LeetCode: Single Number
    sean.jin
    sean.jin
    앱개발, 알고리즘, JS, Kotlin, 미국 취업준비

    티스토리툴바