我需要将大小为 4 的整数数组转换为int
。我见过看起来像 {1, 2, 3, 4} 变成 1234 的数组int
解决方案,我也见过像 {10, 20, 30} 这样的数组会变成 102030 的解决方案。但是,我的问题是我将有一个看起来像 {0, 6, 88, 54} 的数组,而我之前提到的解决方案仅适用于具有相同类型的 int
s 的数组{例如所有一位数或所有两位数}。
我应该怎么做才能解决这个问题?
我从 {0, 6, 88, 54} 数组的预期输出是 68854。
示例 中间带有零的输出应保留它们,即 {6, 0, 0, 8} 将是 6008,但默认情况下 {0, 6, 0, 0, 8} 仍将以int
形式6008
。我在int
中需要这个,但我不介意有一个字符串中间。
你可以做这样的事情:
int res = 0;
int nums[4] = {1, 4, 3, 2}
int i = 0, temp;
for (i = 0; i < 4; ++i) {
temp = nums[i];
do {
res *= 10;
} while ((temp /= 10) > 0);
res += nums[i];
}
这个解决方案呢?
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int arr[] = {0, 6, 88, 54};
char buffer[1000] = { 0 };
for(size_t i = 0; i < sizeof arr / sizeof *arr; ++i)
sprintf(buffer, "%s%d", buffer, arr[i]);
int val = strtol(buffer, NULL, 10);
printf("%dn", val);
return 0;
}
int 打印608854
.
一个简洁的解决方案可能是打印成一个字符串,然后将字符串转换回整数
char dummy[100];
int answer;
int input[4];
....
sprintf(dummy,"%d%d%d%d",input[0],input[1],input[2],input[3]);
answer=atoi(dummy);
sprintf
将整数打印成字符串
atoi
将字符串转换为整数,并且应该能够在前面处理0
。
完整程序
#include <stdio.h>
#include <stdlib.h>
int main()
{
char dummy[100];
int answer;
int input[4]={3,4,0,345};
sprintf(dummy,"%d%d%d%d",input[0],input[1],input[2],input[3]);
answer=atoi(dummy);
printf("%dn",answer);
return 0;
}