📄 dataconversion.java
字号:
import java.io.*;
public class DataConversion {
/*convert a String into an integer
*integer range from -2147483647 to 2147483647
*inputs:
*if the string has some non-digits, just convert the first digits into
*integers and then report errors, ie. "23ab34" -> 23.
*if the string has ., just convert the integer part of the number, ie. "345.2" -> 345
*if the string contains sign of the number, convert it as appropriate
*ie. "+56" -> 56, "-34" -> -34
*/
public int atoi(String s)
{
int s_index = 0; //string index, for conversion
byte num_sign = 1; //sign of the result number
int number = 0; //result number
//check the input string length
if (s.length() <= 0)
{ System.out.println("input string length is incorrect. should be larger than 0");
return 0;
}
//System.out.println("input string is "+s);
//check the sign
if (s.charAt(0) == '-' || s.charAt(0) == '+')
{ if (s.charAt(0) == '-')
num_sign = -1;
s_index = 1;
}
for (int i=s_index; i<s.length(); i++)
{
if (s.charAt(i) >= '0' && s.charAt(i) <= '9')
{
//System.out.println("string at "+i+" is "+s.charAt(i));
number = number*10 + (s.charAt(i) - '0');
}
else {
if (s.charAt(i) != '.')
System.out.println("input string has wrong characters. should be digits 0-9");
break;
}
}
return num_sign*number;
}
// public static void main(String[] args)
// {
// DataConversion mydc = new DataConversion();
// System.out.println("1 is "+mydc.atoi("1"));
// System.out.println("-1 is "+mydc.atoi("-1"));
// System.out.println("+1 is "+mydc.atoi("+1"));
// System.out.println("0 is "+mydc.atoi("0"));
// System.out.println("-0 is "+mydc.atoi("-0"));
// System.out.println("1.2 is "+mydc.atoi("1.2"));
// System.out.println("2-3 is "+mydc.atoi("2-3"));
// System.out.println("299.3a is "+mydc.atoi("299.3a"));
// System.out.println("abc is "+mydc.atoi("abc"));
// System.out.println("a123 is "+mydc.atoi("a123"));
//
// System.out.println("214748" + mydc.atoi("214748"));
// System.out.println(" " + mydc.atio(" "));
// System.out.println("max integer is "+Integer.MAX_VALUE);
// System.out.println("min integer is "+Integer.MIN_VALUE);
//
//
// System.out.println("2147483647 is " + mydc.atoi("2147483647"));
// System.out.println("2147483648 is " + mydc.atoi("2147483648"));
// System.out.println("-2147483647 is " + mydc.atoi("-2147483647"));
// System.out.println("-2147483648 is " + mydc.atoi("-2147483648"));
//
//
// System.out.println("2224859387587563 is " + mydc.atoi("2224859387587563"));
//
// }
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -