codewars – 5kyu —Convert A Hex String To RGB
题目:When working with color values it can sometimes be useful to extract the individual red, green, and blue (RGB) component values for a color. Implement a function that meets these requirements:
Accepts a case-insensitive hexadecimal color string as its parameter (ex. “#FF9933” or “#ff9933”) Returns a Map<String, int> with the structure {r: 255, g: 153, b: 51} where r, g, and b range from 0 through 255 Note: your implementation does not need to support the shorthand form of hexadecimal notation (ie “#FFF”)
Example “#FF9933” --> {r: 255, g: 153, b: 51}
测试代码块部分:
#include <criterion/criterion.h>
typedef struct {
int r, g, b;
} rgb;
void tester(const char *hex_str, rgb expected);
Test(Sample_Tests, should_pass_all_the_tests_provided) {
{
const char *hex_str = "#FF9933";
rgb expected = {255, 153, 51};
tester(hex_str, expected);
}
{
const char *hex_str = "#beaded";
rgb expected = {190, 173, 237};
tester(hex_str, expected);
}
{
const char *hex_str = "#000000";
rgb expected = {0, 0, 0};
tester(hex_str, expected);
}
{
const char *hex_str = "#111111";
rgb expected = {17, 17, 17};
tester(hex_str, expected);
}
{
const char *hex_str = "#Fa3456";
rgb expected = {250, 52, 86};
tester(hex_str, expected);
}
}
解答代码块:
typedef struct {
int r, g, b;
} rgb;
rgb hex_str_to_rgb(const char *hex_str) {
rgb hex_str_to_rgb;
int a[7];
for(int i = 1;i<7;i++){
if((*(hex_str+i)>='0')&&(*(hex_str+i)<='9')){
a[i] = *(hex_str+i) - '0';
}
else if((*(hex_str +i )>='a')&&(*(hex_str+i)<='f')){
a[i] =( *(hex_str+i) - 'a') +10;
}
else if ((*(hex_str +i)>='A')&&(*(hex_str+i)<='F')){
a[i] = (*(hex_str +i)-'A') +10;
}
}
hex_str_to_rgb.r = a[1]*16 + a[2];
hex_str_to_rgb.g = a[3]*16 + a[4];
hex_str_to_rgb.b = a[5]*16 + a[6];
return hex_str_to_rgb;
}
1.结构体的定义,结构体和结构体指针的声明,及对应声明不同后续的调用参数方式不同,点或者箭头。 2.16进制字符如何转换为数字,(同类型的参数可以做加减,例如,‘f’ - ‘a’);
优质解答:
#include <stdio.h>
typedef struct { int r, g, b; } rgb;
rgb hex_str_to_rgb(const char *hex_str) {
int r, g, b;
sscanf(hex_str, "#%2x%2x%2x", &r, &g, &b);
return (rgb){r, g, b};
}
**sccanf函数,描述,C 库函数 int sscanf(const char str, const char format, …) 从字符串读取格式化输入
**声明 下面是 sscanf() 函数的声明。 int sscanf(const char str, const char format, …)
sscanf函数的定义,用法。(https://www.runoob.com/cprogramming/c-function-sscanf.html)
|