C 将两位数字转换为一位整数

标签 c

如何将数组中的两位数转换为一个整数并放入新数组中?

示例:1245678933658 到 [12,45,67,89,33,65,80] 如果是奇数,则在最后添加 0。

我的尝试是:

new_array[i]=digits[i]*10+digits[i++]*10/10;

最佳答案

它是否必须是“一行”,或者是否也允许使用更具可读性的代码?请尝试以下操作:

const char* digits = "12456789336581";
int digitIndex=0;
int numbers[100];
int currentNumberIndex = 0;
int currentNumber = 0;
while (digits[digitIndex]) {
    currentNumber *=10;
    currentNumber += digits[digitIndex] - '0';
    digitIndex++;

    if ( (digitIndex)%2 == 0)  // two digits handled?
    {
        numbers[currentNumberIndex++] = currentNumber;
        currentNumber = 0;
    }
}

// handle the case that last number contained just one digit:
if (digitIndex%2) {
    currentNumber *=10;
    numbers[currentNumberIndex++] = currentNumber;
}

for (int i=0; i < currentNumberIndex; i++)
    printf("number[%d]: %d\n", i, numbers[i]);

关于C 将两位数字转换为一位整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41622362/

相关文章:

c - C 中的任何系统调用都可以在非根用户模式下更改 HP-UX 中文件的权限吗?

c - Union 在使用不同的格式说明符时表现不同

c - 处理\n问题

php - 如何使用 php 处理来自 C 程序的输入

objective-c - 确保内存区域为空白(全部为 NULL)的最快方法?

c - 围绕 OpenSSH 的简单 C 包装器(在 Windows 上使用 Cygwin)

c - 为C中的链表中的新元素分配内存

c - 尝试锁定共享内存互斥体时出现段错误

c - 如何使用iso_8859-1在C程序中输出度数符号?

c - 如何获得2xn矩阵的所有可能组合