重新排列数字块 [英] Rearranging blocks of digits
问题描述
我遇到了一个棘手的问题,我不知道该答案的答案:用递归函数从两个整数中重新排列整数"这是一个例子:
I encountered a hard question I don't know the answer to: "Rearrange the digits from an integer in blocks of two with a recursive function" here's an example:
输入:123456
unsigned long pairinvPrint(unsigned long number) {
printf("%d", number % 100);
if ((number / 100) <= 99) {
printf("%d", number / 100);
}
else {
pairinv(number / 100);
}
}
输出:563412
更多I/O示例:42->42;1234->3412
Output: 563412
More I/O Examples: 42 -> 42; 1234 -> 3412
但是,执行此操作的设置环境很困难(没有循环,数组,指针,全局或静态变量,没有库),并且不应直接打印解决方案,而应在这样的调用时将其返回:
However, the set circumstances to do this are hard (no loops, arrays, pointers, global- or static variables, no libraries) and it should not print the solution directly, rather return it upon a call like this:
printf("Rearrange int (%lu) = %lu", input, pairinvert(input));
幸运的是,有一种情况使输入变得更容易,输入数字的数量始终为偶数.
Luckily there's one circumstance to make it easier, the number of the input digits is always even.
现在我尝试了一段时间,但无法提出一个可行的解决方案,除了使用 printf
的无效解决方案.
Now I experimented for a while, but cant come up with a working solution, except the invalid one using printf
.
有人对我有启发性或想法如何解决这个问题吗?
Does anyone have some inspiration for me or idea how to tackle this?
推荐答案
我会咬:-)
unsigned long p(unsigned long p1, unsigned long p2) {
// no loops, no arrays, no pointers, no global, no static, no variables, no libraries
if (p1 < 100) return p2*100 + p1;
return p(p1/100, p2*100 + p1%100);
}
unsigned long pairinvert(unsigned long n) {
// no loops, no arrays, no pointers, no global, no static, no variables, no libraries
if (n < 100) return n;
return p(n/100, n%100);
}
// need <stdio.h> for printf()
#include <stdio.h>
int main(void) {
unsigned long input;
input = 123456;
printf("Rearrange int (%lu) = %lu\n", input, pairinvert(input));
input = 42;
printf("Rearrange int (%lu) = %lu\n", input, pairinvert(input));
input = 1234;
printf("Rearrange int (%lu) = %lu\n", input, pairinvert(input));
}
这篇关于重新排列数字块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!