您的位置:首页 > 职场人生

面试总结之 代码的完整性和高效性

2013-07-30 05:18 253 查看
例子1:

实现 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));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: