- 首先我要在纸上,非常非常聪明且迅速且机灵,
- 给出几个用例,找出边界用例和特殊用例,确定特判条件;在编码前考虑到所有的条件
- 向面试官提问:问题规模,特殊用例
- 给出函数头
- 暴力解,简述,优化。
- 给出能够想到的最优价
- 伪代码,同时结合用例
- 真实代码
Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
/*
Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
*/
/*
1. get the sign
2. abs
3. transfer the unsign number
3.1 mod 10 to pick the last digit.
3.2 divide 10 to remove the last digit.
3.3 until x == 0
4. restore the sign
*/
int rev_int(int x)
{
int tx = x;
bool sign = (tx>=0);
tx = sign ? tx : -tx;
int ans = 0;
while(tx!=0) // what if the
{
ans*=10;
ans += tx%10;
tx /= 10;
}
return sign ? ans : -ans;
}
本文深入探讨了在编程中如何通过智能算法优化及识别边界与特殊用例来提高代码质量。以反转整数为例,详细介绍了如何考虑问题规模、提出函数头、暴力解法简述、优化策略,并提供了最优伪代码和真实代码实现。重点突出了如何在实际编程中运用这些技巧来解决常见问题。
356

被折叠的 条评论
为什么被折叠?



