본문 바로가기

leetcode

[python][leetcode 2575] Find the Divisibility Array of a String

2575. Find the Divisibility Array of a String
 

You are given a 0-indexed string word of length n consisting of digits, and a positive integer m.

The divisibility array div of word is an integer array of length n such that:

  • div[i] = 1 if the numeric value of word[0,...,i] is divisible by m, or
  • div[i] = 0 otherwise.

Return the divisibility array of word.

 

  한줄요약 : 

나눠지면, 1, 안나눠지면 0 넣기 

 

Input: word = "998244353", m = 3
Output: [1,1,0,0,0,1,1,0,0]
Explanation: There are only 4 prefixes that are divisible by 3: "9", "99", "998244", and "9982443".
 
 필요 개념: 
string을 int로 변환하려면?  int( ) 를 쓰면된다 --- 속도 매우 느리다. 
word의 맨앞에서 부터 하나씩 빼내서 숫자를 만들려면 ?  --- 하나씩 받아다가 10을 곱하면 된다. 
 
POINT2 : 
* 그냥 하면 time limit이 발생한다. s가 m이하로 유지된다면, 숫자가 m이상으로는 증가하지 않을것이다. 
원래 생각했던 s%m으로 진행하면, 나누어지지 않는 수가 반복 될 경우 time limit에 걸릴수있다. 
 
class Solution:
    def divisibilityArray(self, word: str, m: int) -> List[int]:
        n = len(word)
        #curr = 0
        s=0
        ans=[]
        for i in word:
            s=s*10+int(i)
            if s%m==0:
                ans.append(1)
            else:
                ans.append(0)
            s%=m
            
        return ans
 

'leetcode' 카테고리의 다른 글