Problem solving/Algorithms
An array of divisible numbers (나누어 떨어지는 숫자 배열)
Young_A
2020. 9. 10. 07:43
Question
Write the solution which returns an array that includes numbers capable of being divided by a divisor provided and in ascending order.
If there is no divisible number, then return an array contains -1.
Limitation
- arr is an array that includes only natural numbers.
- For integer i and j, if i =! j, then arr[i] =! arr[j].
- The divisor is a natural number.
- array's length is equal or longer than 1.
Example of I/O
arr | divisor | return |
[5, 9, 7, 10] | 5 | [5, 10] |
[2, 36, 1, 3] | 1 | [1, 2, 3, 36] |
[3, 2, 6] | 10 | [-1] |
My Solution
def solution(arr, divisor):
answer = []
for x in arr:
if x%divisor == 0:
answer.append(x)
if len(answer) == 0:
answer.append(-1)
else:
answer.sort()
return answer
Reference