String to Integer

作者分享了自己在解决复杂编程问题时的挑战与思考过程,从最初的盲目尝试到最终通过优化算法实现目标,文章详细阐述了遇到的问题、采取的策略以及最终成功的方法。通过对比自己冗长且低效的代码与官方简洁高效的解决方案,作者反思了代码质量和效率的重要性。此篇博客不仅提供了解决实际编程问题的实例,还强调了在面对复杂任务时保持耐心、深入理解需求和不断优化的重要性。

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

spoilers alert... click to show requirements for atoi.

这道题我觉得挺无趣的,可能是因为OJ题目做的太少,不太清楚各种规则,有些想当然,没有完全理解清楚题意就开始写代码以至于浪费了很长时间。不过有意思的是,当我提交成功之后,系统提示我解锁了一个solution,看了一下官方给的solution,瞬间明白了,好的算法和烂算法的差别。Although I make it possible, I make it ugly。

以下是我冗长的Python代码:

ef atoi(strg):
    illeFigure = False
    fFigure = False
    figure = []
    numList = []
    num = []
    for i  in range(0, 10):
        numList.append(str(i))
    for i in range(0, len(strg)):
        if illeFigure == False:
            if strg[i] == " ":
                continue
            elif strg[i] == "+" or strg[i] == "-":
                illeFigure = True
                fFigure = True
                figure.append(strg[i])
                continue
            elif strg[i] in numList:
                num.append(strg[i])
                illeFigure = True
                continue
            else:
                break
        if illeFigure == True:   
            if strg[i] in numList:
                num.append(strg[i])
                continue
            else:
                break
    if illeFigure == False:
        return 0
    else:
        if len(num) == 0:
            return 0
        d = ''.join(num)
        y = re.findall("[1-9][0-9]*", d)
        if len(y) == 0:
            return 0
        x = ''.join(y)
        print("x is:" + x)
        if fFigure == True:
            if figure[0] == "+":
                if len(x) == 10 and x >= "2147483647":
                    return 2147483647
                elif len(x) > 10:
                    return 2147483647
                else:
                    return int(x)
            if figure[0] == "-":
                if len(x) == 10 and x >= "2147483648":
                    return -2147483648
                elif len(x) > 10:
                    return -2147483648
                else:
                    return int(-int(x))
        if len(x) == 10 and x > "2147483647":
            return 2147483647
        elif len(x) > 10:
            return 2147483647
        else:
            return int(x)

官方高大上的solution:

To deal with overflow, inspect the current number before multiplication. If the current number is greater than 214748364, we know it is going to overflow. On the other hand, if the current number is equal to 214748364, we know that it will overflow only when the current digit is greater than or equal to 8.

private static final int maxDiv10 = Integer.MAX_VALUE / 10;

public int atoi(String str) {
   int n = str.length();
   int i = 0;
   while (i < n && Character.isWhitespace(str.charAt(i))) i++;
   int sign = 1;
   if (i < n && str.charAt(i) == '+') {
      i++;
   } else if (i < n && str.charAt(i) == '-') {
      sign = -1;
      i++;
   }
   int num = 0;
   while (i < n && Character.isDigit(str.charAt(i))) {
      int digit = Character.getNumericValue(str.charAt(i));
      if (num > maxDiv10 || num == maxDiv10 && digit >= 8) {
         return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
      }
      num = num * 10 + digit;
      i++;
   }  
   return sign * num;
}


### 整数转换为字符串的方法 在不同编程语言中,整数转字符串的方式有所差异。 #### Python 中使用 `str()` 函数 Python 提供了一个内置函数`str()`用于将各种数据类型的值转化为字符串形式。对于整数值而言,可以直接调用此函数完成转换操作[^3]。 ```python number = 12345 string_representation = str(number) print(string_representation, type(string_representation)) ``` #### C/C++ 中利用 `sprintf` 或者 `to_string` C++11 及之后的标准库引入了更简便的`std::to_string(int)`方法来实现这一目标;而在较早版本或者纯C环境下,则可以借助`sprintf`这样的格式化输出接口间接达成相同效果[^1]. ```cpp #include <iostream> #include <cstdio> // For sprintf in C style or std::ostringstream for stream approach int main(){ int num = 9876; char buffer[20]; // Buffer size should be large enough. sprintf(buffer,"%d",num); // Using C-style string handling auto cpp_way = std::to_string(num); std::cout << "Using C Style:" << buffer << "\n"; std::cout << "Using CPP Way:"<< cpp_way<<"\n"; return 0; } ``` #### Java 中通过 `String.valueOf()` Java 提供静态工厂方法`String.valueOf(primitive_type/Wrapper_class)`来进行基本类型到其对应的封装类再至字符串之间的转变过程简化处理[^5]. ```java public class Main { public static void main(String[] args){ Integer myIntValue=5678; String convertedStr=String.valueOf(myIntValue); System.out.println(convertedStr+" is now a "+convertedStr.getClass().getName()); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值