回复 9楼 rjsp
汗!!你们的算法我看不太懂,,刚学c还不是很熟。。
回复 5楼 rjsp
这个2的倍数我考虑到了。时间减少一半还是超时,
#include <stdio.h> #include <malloc.h> #include <string.h> // 以下是个变长字符串 struct varstring { char* p; size_t len; size_t capacity; }; void varstring_constructor( struct varstring* vs ) { vs->p = (char*)malloc( 10 ); vs->len = 0; vs->capacity = 10; } void varstring_destructor( struct varstring* vs ) { free( vs->p ); } void varstring_append( struct varstring* vs, char c ) { if( vs->len == vs->capacity ) { char* p = (char*)malloc( vs->capacity*2 ); memcpy( p, vs->p, vs->capacity ); free( vs->p ); vs->p = p; vs->capacity *= 2; } vs->p[vs->len++] = c; } void varstring_reverseprint( struct varstring vs ) { for( size_t index=vs.len; index!=0; --index ) putchar( vs.p[index-1] ); } // 如果第一位数字是f,则这个数值是多少 struct varstring foo( unsigned k, unsigned f ) { struct varstring vs; varstring_constructor( &vs ); unsigned c = 0; // 进位 unsigned a = f; while( vs.len==0 || c!=0 || a!=f ) { unsigned t = a*k+c; a = t%10; c = t/10; varstring_append( &vs, a+'0' ); } return vs; } // 计算第一位是1,是2,是3……,是9 的九种可能,选择其中最小的那个 struct varstring bar( unsigned k ) { struct varstring vss[9]; for( unsigned i=1; i<10; ++i ) vss[i-1] = foo( k, i ); size_t minidx = 0; for( unsigned i=1; i<9; ++i ) { if( vss[i].len < vss[minidx].len ) { varstring_destructor( &vss[minidx] ); minidx = i; } else { varstring_destructor( &vss[i] ); } } return vss[minidx]; } // 这个函数,就是最终你需要的 void baz( unsigned k ) { printf( "%u = ", k ); struct varstring vs = bar(k); varstring_reverseprint( vs ); varstring_destructor( &vs ); putchar( '\n' ); } int main() { baz(4); baz(10); baz(11); //baz(9999); 输出太长就不贴了 return 0; }