使用字符串进行拆分的另一种变体:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int split( int val, int *top, int *bot )
{
char tmp[23]; // should be large enough to hold a 64-bit decimal integer
// plus sign plus 0 terminator
char low[12] = {0};
char high[12] = {0};
if ( val < 0 )
val = -val;
sprintf( tmp, "%d", val );
if ( strlen( tmp ) % 2 )
return 0;
strncpy( low, tmp, strlen( tmp ) / 2 );
strncpy( high, tmp + strlen( tmp ) / 2, strlen( tmp ) / 2 );
*top = (int) strtol( low, NULL, 10 );
*bot = (int) strtol( high, NULL, 10 );
return val;
}
int main( int argc, char **argv )
{
if ( argc < 2 )
{
fprintf( stderr, "USAGE: %s integer_value_with_even_number_of_digits\n", argv[0] );
exit( 0 );
}
int val = (int) strtol( argv[1], NULL, 10 );
int lo, hi;
if ( split( val, &lo, &hi ) )
printf( "val: %d, lo: %d, hi: %d\n", val, lo, hi );
else
fprintf( stderr, "USAGE: %s integer_value_with_even_number_of_digits\n", argv[0] );
exit( 0 );
}
一些示例运行:
[fbgo448@n9dvap997]~/prototypes/splitter: ./splitter 1
USAGE: ./splitter integer_value_with_even_number_of_digits
[fbgo448@n9dvap997]~/prototypes/splitter: ./splitter 12
val: 12, lo: 1, hi: 2
[fbgo448@n9dvap997]~/prototypes/splitter: ./splitter -12
val: -12, lo: 1, hi: 2
[fbgo448@n9dvap997]~/prototypes/splitter: ./splitter -123
USAGE: ./splitter integer_value_with_even_number_of_digits
[fbgo448@n9dvap997]~/prototypes/splitter: ./splitter -1234
val: -1234, lo: 12, hi: 34
[fbgo448@n9dvap997]~/prototypes/splitter: ./splitter 12345678
val: 12345678, lo: 1234, hi: 5678
[fbgo448@n9dvap997]~/prototypes/splitter: ./splitter -1234567890
val: -1234567890, lo: 12345, hi: 67890
[fbgo448@n9dvap997]~/prototypes/splitter: ./splitter 012
val: 12, lo: 1, hi: 2
[fbgo448@n9dvap997]~/prototypes/splitter: ./splitter 00123456
val: 123456, lo: 123, hi: 456
[fbgo448@n9dvap997]~/prototypes/splitter: ./splitter 001234567
USAGE: ./splitter integer_value_with_even_number_of_digits
您没有提到值是否必须为正数,或者前导零是否计入位数(由于它被读取为整数值而不是字符串,因此转换后没有前导零)。
对我来说,这段代码具有简单的优点。我们本质上将数字视为一串数字以从中间拆分,因此(至少在我看来)使用字符串操作似乎是最直接的。在性能方面,这不应该比使用log 获取数字并循环它们慢。