面试总结之 代码的完整性和高效性
2013-07-30 05:18
253 查看
例子1:
实现 double power(double base, int exponent) 求base的exponent 次方. 不需要考虑overflow 问题.
自以为简单的解法:
but above not consider the situation of exponent a .samll or equal than one
b. equal zero
c. is negative
例子2:
char to int 的转换
需要考虑鲁棒性
可以用 global variable 或者 Eception 来解决invaild 输入.
实现 double power(double base, int exponent) 求base的exponent 次方. 不需要考虑overflow 问题.
自以为简单的解法:
public double Power(double base, int exponent) { double result = 1.0; for(int i = 1; i <= exponent; ++i) result *= base; return result; }
but above not consider the situation of exponent a .samll or equal than one
b. equal zero
c. is negative
例子2:
char to int 的转换
需要考虑鲁棒性
可以用 global variable 或者 Eception 来解决invaild 输入.
import java.util.ArrayList; import java.util.Arrays; public class test{ enum Status {kValid, KInvalid}; static Status g_nStatus = Status.kValid; public int StrToInt1(char[] str) throws Exception { if(str==null) throw new Exception("null"); return 0; } public static int StrToInt(char[] str) { //null //"" //+,- //invaild input int num = 0; int i = 0; System.out.println(str.length); if(str!= null && str.length !=0) { boolean minus = false; if(str[0]=='+') i++; else if(str[0]=='-') { i++; minus = true; } if(str.length > 1) { num = StrToIntCore(str,i,minus); } } return num; } public static int StrToIntCore(char[] str,int index, boolean minus) { long num = 0; int i = index; int length = str.length; while(i<length) { if(str[i] >= '0' && str[i] <= '9') { int flag = minus ? -1 : 1; num = num*10 + flag*(str[i]-'0'); if((!minus && num > Integer.MAX_VALUE)||(minus && num < Integer.MIN_VALUE)) { throw new RuntimeException("overflow"); } }else { throw new RuntimeException("invaild input"); // or num = 0; break; } i++; } if(i == length) { g_nStatus = Status.kValid; } return (int) num; } public static void main(String[] args) { // TODO Auto-generated method stub char[] array = {'1','2','3'}; char[] array1 = {}; char[] array2 = {'+','2','3'}; char[] array3 = {'-','2','3'}; char[] array4 = {'-','2','-'}; System.out.println(StrToInt(array4)); } }
相关文章推荐
- Trie树的常见应用大总结(面试+附代码实现)
- 常见面试代码总结
- 读《编程之美》_面试杂谈_代码总结
- 面试之路(24)-提高代码的规范性,完整性,错误处理
- 面试必会代码总结
- Trie树的常见应用大总结(面试+附代码实现)
- 链表的一些常见笔试面试问题总结及代码
- Trie树的常见应用大总结(面试+附代码实现)
- C++代码优化方法总结
- 开学面试笔试总结
- html基础,写代码时的总结等---ShinePans
- 面试中的排序算法总结
- 如何阅读别人的代码——有点感触,总结的还可以,有帮助
- 逻辑回归的常见面试点总结
- android 面试总结(2)
- 2016-11-15面试总结
- 李洪强经典面试总结16
- 2014.09.05面试总结
- 互联网公司面试问题总结之网络和操作系统
- 为java程序员整理的面试、编码、技巧、资源总结