题目来源:
庞果网
题目描述:
题目很简单,完成函数reverse,要求实现把给定的一个整数取其相反数的功能,举两个例子如下: x = 123, return 321 x = -123, return -321
代码(可在anycodex编译通过, try yourself?):
#include<stdio.h>
#include <stdlib.h>
int reverse(int x) {
//write your code here
int temp = x;
int count = 1;
int *a; //存放每一位数值的数组
int i = 0;
int bit = 0;
int result = 0;
int bitFlag = 1;
while(temp/10 != 0)
{
temp = temp/10;
count++;
}
a = (int *)malloc(count * sizeof(int)); //动态分配数组
temp = x;
for (; i < count; i++)
{
bit = temp % 10;
*(a + i) = bit;
temp = temp / 10;
//printf("The value in the box is %d\n", *(a+i)); //将N的每一位都放入数组中
}
for(i = count - 1; i >= 0; i--)
{
//printf("The value in the matrix is %d ", *(a+i));
result += *(a + i) * bitFlag;
bitFlag *= 10;
}
return result;
}
//start 提示:自动阅卷起始唯一标识,请勿删除或增加。
int main()
{
int N = -123;
int result;
result = reverse(N);
printf("result is %d\n", result);
return 0;
}
//end //提示:自动阅卷结束唯一标识,请勿删除或增加。