问题描述
小M需要一个函数,用于将RGB颜色值转换为相应的十六进制整数值。RGB色值以字符串的形式给出,如"rgb(192, 192, 192)"
,需要转换为对应的整数值。
代码
import re
def solution(rgb):
# Please write your code here
mc = re.findall(r'\d+', rgb)
if not mc or len(mc) != 3:
raise ValueError('Invalid rgb')
mc = list(map(int, mc))
if any(d < 0 or d > 255 for d in mc):
raise ValueError('Invalid rgb')
# Method 1: Using bitwise operations
result1 = (mc[0] << 16) + (mc[1] << 8) + mc[2]
# Method 2: Using formatted string and parsing to int
result2 = int(''.join(f'{x:02x}' for x in mc), 16)
if result1 == result2:
return result1
raise ValueError
if __name__ == "__main__":
# You can add more test cases here
print(solution("rgb(192, 192, 192)") == 12632256 )
print(solution("rgb(100, 0, 252)") == 6553852)
print(solution("rgb(33, 44, 55)") == 2174007)