向前,还是向后?
假设一个正整数:
unsigned int n = 1191223;
while (n != 0) {
doSomething (n % 10);
n /= 10;
}
…将从最小到最大工作,或者…
EDIT我已经忘记了我在这里的这个不起作用的解决方案。请注意,Very Smart People™ 似乎始终使用最小到最大的迭代(Linux 内核和 GLibC 的printf
,例如,只是向后迭代),但如果你真的不想使用,这是一个糟糕的方法snprintf
因为某些原因…
int left_to_right (unsigned int n) {
unsigned int digit = 0;
if (0 == n) {
doSomething (0);
} else {
digit = pow(10, 1.0+ floor(log10(n)));
while (digit /= 10) {
doSomething ( (n / digit) % 10 );
}
}
}
我认为假设你有是非常愚蠢的log10
and pow
但不是snprintf
,所以替代计划是
int left_to_right_fixed_max (unsigned int n) {
unsigned int digit = 1000000000; /* make this very big */
unsigned int n10 = 10 * n;
if (0 == n) {
doSomething (0);
} else {
while (digit > n10) { digit /= 10; }
while (digit /= 10) {
doSomething ( (n / digit) % 10 );
}
}
}
…或者,如果您确实没有硬件乘法/除法,您可以求助于使用十的幂表。
int left_to_right (unsigned int n) {
static const unsigned int digit [] =
{ 1,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000 /* make this very big */
};
static const unsigned char max_place = 10;
/* length of the above array */
unsigned char decimal;
unsigned char place;
unsigned char significant = 0; /* boolean */
if (0 == n) {
doSomething (0);
} else {
place = max_place;
while (place--) {
decimal = 0;
while (n >= digit[place]) {
decimal++;
n -= digit[place];
}
if (decimal | significant) {
doSomething (decimal);
significant |= decimal;
}
}
}
}
……我改编自http://www.piclist.com/techref/language/ccpp/convertbase.htm http://www.piclist.com/techref/language/ccpp/convertbase.htm变成一个更通用的版本。