日期:2014-05-20  浏览次数:20759 次

网上看到段自定义的getInt()来替代cin.nextInt(),不是很明白
自定义的代码 getInt() 在空间开销上只有 nextInt() 的1/30,
然后代码里的"45"、"48"哪里来的?求点拨~
代码如下:
public static BufferedInputStream bis = new BufferedInputStream(System.in);

public static int getInt() throws IOException
{
int i;

while ((i = bis.read()) < 45)
;
// if(i==-1)
// return -1;

int temp = 0, mark = 1;

if (i == 45)
{
mark = -1;
i = bis.read();
}

while (i > 47)
{
temp = temp * 10 + i - 48;
i = bis.read();
}

return mark * temp;
}
nextInt()

------解决方案--------------------
45对应ascii字符的-,48对应ascii字符的0,实际上这个数字是以字符串的方式存在文件中的,每次读取一个字符。

if (i == 45)  判断第一个字符是不是负号

temp = temp * 10 + i - 48;   将字符转换成对应的数字,并且没增加一位,则将前面的数字乘以10
------解决方案--------------------
上网上查个ASCII对照表,把45这些跟表里比对下就知道了.