Open guodongxiaren opened 4 years ago
2015年我参加腾讯实习生的笔试题。
#include <stdio.h>
int main() {
int i = ~0; // -1
int n = 0;
while (i) {
n++;
i <<= 1;
}
printf("%d\n", n); // 32
return 0;
}
#define max2(x, y) ((x) > (y) ? (x) : (y))
#define max3(x, y, z) ((x) > (y) ? ((x) > (z) ? (x) : (z)): ((y) > (z) ? (y) : (z)))
#include <stdio.h>
int check() {
int t = 1;
return *(char*)&t;
}
int main() {
int i = check();
if (1 == i)
printf("是小端\n");
else if (1 != i)
printf("是大端\n");
return 0;
}
或者:
unsigned long int i = 0x12345678;
char *p = (char*)&i;
if (*p == 0x78)
cout << "是小端" << endl;
else
cout << "是大端" << endl;
思路其实差不多:
#include <stdio.h>
union {
int number;
char s;
}test;
int testLittleEndin() {
test.number = 0x12345678;
return (test.s == 0x78);
}
int main() {
if (testLittleEndin())
printf("是小端\n");
else
printf("是大端\n");
}
线程安全
class A {
private:
A(){};
A(const A&) = delete;
A& operator = (const A&) = delete;
static A* _a;
public:
static A* get_instance() {
return _a;
}
};
A* A::_a = new A;
注意static变量的初始化。
在需要的时候再创建对象。
class A {
private:
A(){};
A(const A&) = delete;
A& operator = (const A&) = delete;
public:
static A* get_instance0() {
static A* a = new A;
return a;
}
// 或
static A* get_instance1() {
static A a;
return &a;
}
// 也可以返回引用
static A& get_instance2() {
static A a;
return a;
}
};
通常有个引用的版本,被称为Meyers' Singleton。 这种写法只有C++11才有效,因为支持Magic static的特性。使得多线程初始化static的时候,其他线程会阻塞。貌似C++11之前不能保证。 注意引用版本,赋值的时候也需要是引用。因为拷贝构造函数被delete了。
A& a = A::get_instance3();
还有double check的那些。感觉写起来都不优雅。
判断栈增长方向
在某个未知的平台上,不确定栈是向上还是向下增长的。试着判断!