zoukankan      html  css  js  c++  java
  • C# 字符串转换成整数

    csdn的一个题目,看了这篇文章后,就写了个C#的实现方式。

    实现StrToInt方法,以下是代码:

            /// <summary>
            /// 将字符串转化为整数
            /// </summary>
            /// <param name="str"></param>
            /// <returns></returns>
            private static int StrToInt(string str)
            {
                long value = 0;
                if (string.IsNullOrEmpty(str))
                {
                    return (int)value;
                }
    
                bool isNagetive = false;
                char[] ch = str.ToCharArray();
    
                int i = 0;
    
                while (i < ch.Length && ch[i] == ' ')
                    i++;
    
                if (i < ch.Length && (ch[i] == '-' || ch[i] == '+'))
                {
                    if (ch[i] == '-')
                    {
                        isNagetive = true;
                    }
                    i++;
                }
    
                while (i < ch.Length)
                {
                    if (ch[i]<'0'||ch[i]>'9')
                    {
                        break;
                    }
                    
                    if (isNagetive)
                    {
                        value = value * 10 - (ch[i] - '0');
                        value = value < int.MinValue ? int.MinValue : value; //溢出处理
                    }
                    else
                    {
                        value = value * 10 + (ch[i] - '0');
                        value = value > int.MaxValue ? int.MaxValue : value; //溢出处理
                    }
                        
    
                    i++;
                    
                }
    
                return (int)value;
            }
  • 相关阅读:
    Finding Palindromes POJ
    吉哥系列故事——完美队形II HDU
    Period II FZU
    生日礼物&&Supermarket
    炮兵阵地[状态压缩DP]
    最小表示法 P1368
    Period
    最长异或路径
    Luogu P5490 扫描线
    解方程
  • 原文地址:https://www.cnblogs.com/kangs/p/3129123.html
Copyright © 2011-2022 走看看