迅雷有这么一道笔试题,编程计算2的1024次方。
所谓2的1024次方,就是有1024个2相乘,于是有些同学顺手就能写出代码:
int main() { int reslut = 1; for (int i = 0; i < 1024; i++) { result *= 2; } printf("%d ", result); return 0; }如果你也这样写代码,那简历上顶多能写了解C语言,离掌握和精通还差很远。
#include在牛客的排行榜上,速度最快,占用空间最小的并不是这种解法。#include void reverse(char *r) { int length = strlen(r); int i; char ch; for (i = 0; i < length / 2; i++) { ch = r[i]; r[i] = r[length - 1 - i]; r[length - 1 - i] = ch; } } void NPowerOfTwo(int n, char *res) { int i, length, j, num, carry; for (i = 0; i < n; i++) { carry = 0; for (j = 0; j < strlen(res); j++) { num = res[j] - '0'; num = (num << 1) + carry; carry = num / 10; res[j] = num % 10 + '0'; } if (carry > 0) res[j] = carry + '0'; } reverse(res); } int main( ) { int n; char result[2048] = {'1'}; NPowerOfTwo(1024, result); printf("%s ", result); return 0; }
int main() { long double reslut = 1.0; for (int i = 0; i < 1024; i++) { result *= 2.0; } printf("%.0Lf ", result); return 0; }
全部0条评论
快来发表一下你的评论吧 !