guodongxiaren / OJ

4 stars 3 forks source link

编程杂题:显微无间 #35

Open guodongxiaren opened 4 years ago

guodongxiaren commented 4 years ago

判断栈增长方向

在某个未知的平台上,不确定栈是向上还是向下增长的。试着判断!

#include <stdio.h>
#include <stdlib.h>

void func1(){
    int a = 0;
    func2(&a);
}
void func2(int *a){
    int b = 0;
    printf("%x\n%x\n",a,&b);
}

int main(int argc, char** argv) {
    func1();
    return 0;
}
guodongxiaren commented 4 years ago

不用sizeof求int字节数

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;
}
guodongxiaren commented 4 years ago

宏定义实现max

#define max2(x, y) ((x) > (y) ? (x) : (y))
#define max3(x, y, z) ((x) > (y) ? ((x) > (z) ? (x) : (z)):  ((y) > (z) ? (y) : (z)))
guodongxiaren commented 4 years ago

如何查看自己电脑是大端还是小端

方式一:

 #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;

方式二:union

思路其实差不多:

#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");
}
guodongxiaren commented 4 years ago

单例模式

饿汉(饥汉)

线程安全

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的那些。感觉写起来都不优雅。