题目:字符串转换为整数。

思路:将字符串转化为整数首先是遍历字符串中的每一个字符,有三种情况:首字符是正号,首字符是负号,首字符非正负号;然后遍历每一个字符进行num = num * 10 + charArray[i] - '0',在进行这个工作之前首先需要对charArray[i]进行是否为数字字符的判断,循环遍历直到结束,输出结果;

注意事项(思考点):(1)字符串中包含有非数字字符;(2)字符串中包含正负符号;(3)考虑最大的正整数;(4)考虑最小的负整数;(4)溢出。

开始时我的想法只考虑了第一,第二种情况:


 
  1. /**

  2. * 将字符串转换为整数 1:非数字字符 2:正负号

  3. * @author Peter

  4. */

  5. public class Main {

  6. public static void main(String[] args) {

  7. Scanner sc = new Scanner(System.in);

  8. String str = sc.nextLine();

  9. int length = str.length();

  10. int number = 0;

  11. char[] charArray = str.toCharArray();

  12. if (charArray[0] == '-') {

  13. for (int i = 1; i < length; i++) {

  14. if (charArray[i] > '9' || charArray[i] < '0') {

  15. System.out.println("输入的字符串中包含非数字字符");

  16. return;

  17. } else {

  18. number = number * 10 + charArray[i] - '0';

  19. }

  20. }

  21. System.out.println(-number);

  22. } else if (charArray[0] == '+') {

  23. for (int i = 1; i < length; i++) {

  24. if (charArray[i] > '9' || charArray[i] < '0') {

  25. System.out.println("输入的字符串中包含非数字字符");

  26. return;

  27. } else {

  28. number = number * 10 + charArray[i] - '0';

  29. }

  30. }

  31. System.out.println(number);

  32. } else {

  33. for (int i = 0; i < length; i++) {

  34. if (charArray[i] > '9' || charArray[i] < '0') {

  35. System.out.println("输入的字符串中包含非数字字符");

  36. return;

  37. } else {

  38. number = number * 10 + charArray[i] - '0';

  39. }

  40. }

  41. System.out.println(number);

  42. }

  43. }

  44. }

源码(考虑了上面所有情况):


 
  1. package com.chap01.offer01;

  2.  
  3. import java.util.Scanner;

  4.  
  5. /**

  6. * 字符串转整形源码

  7. */

  8. public class Main1 {

  9.  
  10. /**

  11. * 将字符串转化为整形

  12. * @param s

  13. * @return

  14. * @throws NumberFormatException

  15. */

  16. public static int parseInt(String s) throws NumberFormatException {

  17. return parseInt(s, 10);

  18. }

  19.  
  20. /**

  21. * 将字符串转化为整形,其中radix代表基数,即代表你输入的是几进制的字符串。

  22. * @param s

  23. * @param radix

  24. * @return

  25. * @throws NumberFormatException

  26. */

  27. public static int parseInt(String s, int radix)

  28. throws NumberFormatException {

  29. /*

  30. * WARNING: This method may be invoked early during VM initialization

  31. * before IntegerCache is initialized. Care must be taken to not use the

  32. * valueOf method.

  33. */

  34.  
  35. //判断是否为空

  36. if (s == null) {

  37. throw new NumberFormatException("null");

  38. }

  39.  
  40. //判断不能小于2进制

  41. if (radix < Character.MIN_RADIX) {

  42. throw new NumberFormatException("radix " + radix

  43. + " less than Character.MIN_RADIX");

  44. }

  45.  
  46. //判断不能大于36进制 0-9,a-z一共36进制

  47. if (radix > Character.MAX_RADIX) {

  48. throw new NumberFormatException("radix " + radix

  49. + " greater than Character.MAX_RADIX");

  50. }

  51.  
  52. int result = 0;

  53. boolean negative = false;

  54. int i = 0, len = s.length();

  55. int limit = -Integer.MAX_VALUE; //-0x7fffffff即:-2147483647

  56. int multmin;

  57. int digit;

  58.  
  59. if (len > 0) {

  60. char firstChar = s.charAt(0); //取首字符

  61. if (firstChar < '0') { // Possible leading "+" or "-"

  62. if (firstChar == '-') {

  63. negative = true;

  64. limit = Integer.MIN_VALUE; //0x80000000

  65. } else if (firstChar != '+')

  66. throw NumberFormatException.forInputString(s);

  67.  
  68. if (len == 1) // Cannot have lone "+" or "-"

  69. throw NumberFormatException.forInputString(s);

  70. i++;

  71. }

  72. multmin = limit / radix; //-214748364

  73. while (i < len) {

  74. // Accumulating negatively avoids surprises near MAX_VALUE

  75. digit = Character.digit(s.charAt(i++), radix); //返回指定基数的数值

  76. if (digit < 0) {

  77. throw NumberFormatException.forInputString(s);

  78. }

  79. if (result < multmin) {

  80. throw NumberFormatException.forInputString(s);

  81. }

  82. result *= radix; //字符abc: a*100 + b*10 + c

  83. if (result < limit + digit) {

  84. throw NumberFormatException.forInputString(s);

  85. }

  86. result -= digit;

  87. }

  88. } else {

  89. throw NumberFormatException.forInputString(s);

  90. }

  91.  
  92. return negative ? result : -result;

  93. }

  94.  
  95. public static void main(String[] args){

  96. Scanner sc = new Scanner(System.in);

  97. String str = sc.nextLine();

  98. int num = parseInt(str);

  99. System.out.println(num);

  100. }

  101. }


 
  1. package com.chap01.offer01;

  2. //异常类

  3. public class NumberFormatException extends IllegalArgumentException {

  4. static final long serialVersionUID = -2848938806368998894L;

  5.  
  6. /**

  7. * Constructs a <code>NumberFormatException</code> with no detail message.

  8. */

  9. public NumberFormatException() {

  10. super();

  11. }

  12.  
  13. /**

  14. * Constructs a <code>NumberFormatException</code> with the specified detail

  15. * message.

  16. *

  17. * @param s

  18. * the detail message.

  19. */

  20. public NumberFormatException(String s) {

  21. super(s);

  22. }

  23.  
  24. /**

  25. * Factory method for making a <code>NumberFormatException</code> given the

  26. * specified input which caused the error.

  27. *

  28. * @param s

  29. * the input causing the error

  30. */

  31. static NumberFormatException forInputString(String s) {

  32. return new NumberFormatException("For input string: \"" + s + "\"");

  33. }

  34. }

 

10-06 09:48