seungriyou / algorithm-study

알고리즘 & SQL 문제 풀이 기록
https://leetcode.com/u/summer_y
0 stars 0 forks source link

[Tip] Ceil (Round Up) & Floor (Round Down) 구현하기 #102

Open seungriyou opened 3 months ago

seungriyou commented 3 months ago

xy로 나누는 상황에서, 결과 값의 올림과 내림을 구해보자.


Ceil (Round Up)

def ceil(x, y):
    return (x - 1) // y + 1
def ceil(x, y):
    q, r = divmod(x, y)
    return q + (1 if r else 0)
>>> ceil(5, 2)
3
>>> ceil(-5, 2)
-2

>>> ceil(6, 3)
2
>>> ceil(-6, 3)
-2

>>> ceil(5, 3)
2
>>> ceil(-5, 3)
-1


Floor (Round Down)

def floor(x, y):
    return x // y
>>> floor(5, 2)
2
>>> floor(-5, 2)
-3

>>> floor(6, 3)
2
>>> floor(-6, 3)
-2

>>> floor(5, 3)
1
>>> floor(-5, 3)
-2


Related Problems


References