함수 좀 만들어주세요..

leolo의 이미지

int i = 123456;

x(2, 2) 결과는 56
x(4, 2) 결과는 34
x(6, 2) 결과는 12
x(1, 2) 결과는 에러 출력 -1
x(3, 2) 결과는 45
x(3, 3) 결과는 456

보시면, x 라는 함수의 첫번째 인자는 정수의 시작 점이고요. 두번째 인자는
개수입니다.
즉, x(2, 2)의 경우 정수 i에서 시작점(뒤에서 두번째) 5, 그리고, 개수는 2개 따라서, 56이됩니다.
이 함수를 문자열로 변환하지 않고, 오직 정수형을 이용하여 x함수를 구현해야하는데요.
부탁드립니다.

kslee80의 이미지

어떤 용도이실지는 모르겠지만, 필요하다면 골머리 썩혀가면서 만들어 보는것이
더 좋답니다.

int x(int p, int c)
{
    int j, div;
    int ret;

    if(p < c)
        return -1;

    div = 1;
    for(j = 0; j < p; j++)
        div *= 10;

    ret = 0;
    for(j = 0; j < c; j++) {
        ret *= 10;
        ret += (i % div) / (div/10);
        div /= 10;
    }

    return ret;
}
verve의 이미지

#include <stdio.h>
#include <math.h>

int x(int, int);

int main(void)
{
	int res = x(2,2);
	printf("%d\n", res);
	res = x(4,2);
	printf("%d\n", res);
	res = x(6,2);
	printf("%d\n", res);
	res = x(1,2);
	printf("%d\n", res);
	res = x(3,2);
	printf("%d\n", res);
	res = x(3,3);
	printf("%d\n", res);
	return 0;
}

int x(int a, int b)
{
	int i = 123456;

	if (a < b)
		return -1;
	else
		return (i % (int)pow(10,a)) / (int)pow(10,a-b);
}

--
The best way to be happy is to make other people happy! - Larry Wall

leolo의 이미지

감쏴합니다.

실력이 있으면 삶이 편하다... 영차 영차...