代码的完整性
从三个方面确保代码的完整性
应聘者在写代码之前,首先要把可能的输入都想清楚,从而避免在程序中出现各种各样的质量漏洞。通常我们从功能测试、边界测试和负面测试三个方面设计测试用例。
三种错误处理的方式
第一种方式是函数用返回值来告知调用者是否出错。
第二种方式是当错误发生时设置一个全局变量。
第三种方式是异常。
面试题16 数值的整数次方
题目
思考
乍一看的话很容易忽略指数可能是负数,也不会想到要考虑超时的情况,想要有对运行时间进行优化,可以采用模幂算法。
代码
class Solution {
public:
double myPow(double x, int n) {
if(x == 0) {
return 0;
}
if(x == 1.0) {
return 1;
}
long m = n;
double res = 1.0;
if(m < 0) {
//取倒数
x = 1/x;
m = -m;
}
while(m) {
//SQUARE-AND-MULTIPLY EXPONENTIATION ALGORITHM
if((m & 1) == 1) res *= x;
x *= x;
//取下一位
m >>= 1;
}
return res;
}
};
面试题17 打印从1到最大的n位数
题目
思考
大数可用字符串表示,但字符串进位操作复杂,可以转换思路,使用全排列的方法将字符串每一位从’0’到’9’取值。
代码
class Solution {
public:
vector<int>res;
void numprint(string s) {
//去除前置0
bool iszero = true;
string temp = "";
for(auto a:s) {
if(iszero == true && a!='0') {
iszero = false;
}
if(iszero == false) {
temp = temp + a;
}
}
if(temp != "") res.push_back(stoi(temp));
}
//全排列
void dfs(string s, int len, int pos) {
//跳出条件
if(pos == len) {
numprint(s);
//记得返回
return;
}
for(int i = 0; i < 10; i++) {
s[pos] = i + '0';
dfs(s, len, pos+1);
}
}
vector<int> printNumbers(int n) {
//将s初始化填满'0'
string s(n, '0');
dfs(s, s.size(), 0);
return res;
}
};
面试题18 删除链表的节点
题目
思考
要考虑删除的是头结点的情况。
代码
法一:记录前置节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
if(head == nullptr) {
return nullptr;
}
ListNode* dummy = new ListNode(-1);
dummy->next = head;
//要记录前置节点
ListNode* pre = dummy;
while(head != nullptr) {
if(head->val == val) {
pre->next = head->next;
}
pre = pre->next;
head = head->next;
}
return dummy->next;
}
};
法二:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
if(head == nullptr) {
return nullptr;
}
if(head->val == val) {
return head->next;
}
ListNode* cur = head;
while(cur!= nullptr && cur->next != nullptr) {
if(cur->next->val == val) {
cur->next = cur->next->next;
}
cur = cur->next;
}
return head;
}
};