[关闭]
@zsh-o 2018-09-19T09:39:45.000000Z 字数 751 阅读 1431

整形字符串转数字(INT) - 越界判断

算法


  1. #include <stdio.h>
  2. #include <string.h>
  3. const int INT_MAX = 2147483647;
  4. const int INT_MIN = (-INT_MAX - 1);
  5. const int MAXS = 1e5 + 1;
  6. char S[MAXS];
  7. int len;
  8. int char2int(char c){
  9. return (int)(c - '0');
  10. }
  11. int main(){
  12. scanf("%s", S);
  13. len = strlen(S);
  14. int sum = 0;
  15. bool negative = false;
  16. bool overbound = false;
  17. if(S[0] == '-'){
  18. negative = true;
  19. }
  20. else if(S[0] <= '9' && S[0] >= '0'){
  21. sum += char2int(S[0]);
  22. }
  23. for(int i=1; i< len; i++){
  24. if(S[i] <= '9' && S[i] >= '0'){
  25. int t = char2int(S[i]);
  26. // 判断是否越界
  27. if(negative == false){
  28. if(sum > INT_MAX / 10){
  29. overbound = true;
  30. sum = INT_MAX;
  31. break;
  32. }
  33. sum *= 10;
  34. if(INT_MAX - sum < t){
  35. overbound = true;
  36. sum = INT_MAX;
  37. break;
  38. }
  39. sum += t;
  40. }else{
  41. if(sum < INT_MIN / 10){
  42. overbound = true;
  43. printf("1-------\n");
  44. sum = INT_MIN;
  45. break;
  46. }
  47. sum *= 10;
  48. if(INT_MIN - sum > -t){
  49. overbound = true;
  50. sum = INT_MIN;
  51. break;
  52. }
  53. sum -= t;
  54. }
  55. }
  56. else{
  57. break;
  58. }
  59. }
  60. printf("%d\n", sum);
  61. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注