class Solution: def stringToInt(self, value): """ :type value: an ascii string :return type: integer """ #if value contains white space value = value.strip() res = [] for i in range(len(value)): if i == 0 and value[i] in ('+', '-'): res.append(value[i]) elif "0" <= value[i] <= "9": res.append(value[i]) else: return None if res in ([], ['+'], ['-']): return None ans = int(''.join(res)) max, min = 2147483647, -2147483648 if min <= ans <= max: return ans elif ans >= max: return max else: return min def getVal(self): value = raw_input("Enter a value: ") ans = self.stringToInt(value) if ans != None: print "You entered:" + str(ans) else: print "You entered an invalid value!" if __name__ == "__main__": s = Solution() s.getVal()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question