当前位置:首页 > 开发教程 > 软件工程 >

【Leetcode】String to Integer (atoi)

时间:2016-06-06 23:26 来源: 作者: 收藏

Linux系统提供API函数sched_setaffinity和sched_getaffinity用于设置或获取线程的可以使用的CPU核。int sched_setaffinity(pid_t pid, unsigned int cpusetsize, cpu_set_t *mask);这个函数中pid表示需要设置或获取绑定信息的线程id(或进程id),如果为0,表

题目链接:https://leetcode.com/problems/string-to-integer-atoi/
题目:

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.

思路:
各种边界会烦死人的。。。

算法:

[java] view plain copy  【Leetcode】String to Integer (atoi)【Leetcode】String to Integer (atoi)
  1. public int myAtoi(String str) {  
  2.     if (str == null || str.equals(""))  
  3.         return 0;  
  4.     str = str.trim();  
  5.     String flag = "+";  
  6.     int i = 0;  
  7.     if ("+".equals(str.charAt(0) + "")) {  
  8.         i++;  
  9.         flag = "+";  
  10.     } else if ("-".equals(str.charAt(0) + "")) {  
  11.         i++;  
  12.         flag = "-";  
  13.     }  
  14.     double sum = 0;  
  15.     while (i < str.length() && str.charAt(i) <= '9' && str.charAt(i) >= '0') {  
  16.         sum = sum * 10 + Integer.parseInt("" + str.charAt(i));  
  17.         i++;  
  18.     }  
  19.     if (flag.equals("-")) {  
  20.         sum = -sum;  
  21.     }  
  22.     if (sum > Integer.MAX_VALUE) {  
  23.         sum = Integer.MAX_VALUE;  
  24.     }  
  25.     if (sum < Integer.MIN_VALUE) {  
  26.         sum = Integer.MIN_VALUE;  
  27.     }  
  28.     return (int) sum;  
  29. }  
0
0