[2025/05/30]TIL

오수호·2025년 5월 30일

TIL

목록 보기
24/60

Code Kata 문제풀이

문제

The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 - 255. Any values that fall out of that range must be rounded to the closest valid value.

Note: Your answer should always be 6 characters long, the shorthand with 3 will not work here.

Examples (input --> output):
255, 255, 255 --> "FFFFFF"
255, 255, 300 --> "FFFFFF"
0, 0, 0 --> "000000"
148, 0, 211 --> "9400D3"

해결 방법

public class Kata
{
  public static string Rgb(int r, int g, int b) 
  {
    string[] val = new string[]{"A","B","C","D","E","F"}; // 10이 넘어가는 경우 16진수
    int[] colorInput = new int[]{r,g,b}; // rgb값 반복문 돌리기 위한 배열
    string RGB ="";
    
    for(int i = 0 ; i < 3 ; i ++){
      
      if ( colorInput[i] > 255 )
        {
            colorInput[i] = 255;        
        }
      
      if ( colorInput[i] < 0){
        
          colorInput[i] = 0;
      }
      string temp;
      
      temp = colorInput[i]/16>9?val[(colorInput[i]/16) - 10]:(colorInput[i]/16).ToString();
      temp += colorInput[i]%16>9?val[(colorInput[i]%16) - 10]:(colorInput[i]%16).ToString();
      RGB += temp;
      
    }
    
    return RGB;
  }
}
profile
게임개발자 취준생입니다

0개의 댓글