무냐의 개발일지

[코딩테스트] sqrt 씌우기 (** 쓰지 않고), Deci-Binary더하기 숫자, 배열 더하기 본문

LeetCode 코딩테스트

[코딩테스트] sqrt 씌우기 (** 쓰지 않고), Deci-Binary더하기 숫자, 배열 더하기

무냐코드 2024. 4. 11. 00:01

69. Sqrt(x)

 

내가 직관적으로 푼 건 아래와 같은데, 소요시간이 좀 더 길게 나왔다

# if cannot use **0.5
class Solution:
    def mySqrt(self, x):
    # 1,4,9,16,25,36,49,64,81,100 
    # 1(3), 2(5), 3(7), 4(9), 5(11), 6(13)... 홀수개다 
        for i in range(x+1):
            if x in range(i**2, ((i+1)**2)):
                return int(i)

 

 

좀 더 모범적인 답안은 아래와 같다

class Solution:
    def mySqrt(self, x: int) -> int:
        left,right=1,x
        while left<=right:
            mid=(left+right)//2
            if mid*mid==x:
                return mid
            if mid*mid>x:
                right=mid-1
            else:
                left=mid+1
        return right

 

 

 

 

1689. Partitioning Into Minimum Number Of Deci-Binary Numbers

 

A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary, while 112 and 3001 are not.

Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n.

Example 1:
Input: n = "32"
Output: 3
Explanation: 10 + 11 + 11 = 32

 

Example 2:
Input: n = "82734"
Output: 8

 

풀이

class Solution:
    def minPartitions(self, n: str) -> int:
        return int(max(n))

 

 

너무 잘했다. 어차피 더해봤자 가장 크게 나올 수 있는 갯수는 9가 최대이다. 그 말은, 숫자 안에서 가장 큰 int값이 곧 더해야할 0,1만으로 이뤄진 숫자의 갯수랑 같다는 뜻이다. 내 힘으로 풀었다 ! 

 

 

 

1929. Concatenation of Array

배열을 더하는 방법에는 여러가지가 있다

A = [1,3,2,1]
B = [1,3,2,1]

두 Array가 있을 때,

 

1. +

A+B = [1,3,2,1,1,3,2,1]  단순히 더하는 것만으로도 그냥 합쳐진다.

class Solution:
    def getConcatenation(self, nums: List[int]) -> List[int]:
        return nums + nums

 

2. append()

여기서 만약에 append를 쓰게 되면, append() 메서드는 리스트에 요소를 추가하는 데 사용므로, 추가할 수 있는 것은 리스트 자체가 아니라 리스트에 속한 요소이다. [1,3,2,1, [1,3,2,1]] 이런 식으로 요소로 추가된다

 

3. extend()

       nums.extend(nums)

이렇게 써도 동일하게 추가가 가능하다. extend() 함수는 리스트에 다른 리스트의 모든 요소를 추가하는 메서드다. 

append() 메서드와는 달리, extend()는 리스트에 리스트를 추가할 때 그 리스트의 각 요소를 개별적으로 추가한다. 이 경우에 매우 적합한 함수라고 생각하면 된다.