为什么略去了4、5、6题呢,真的是血崩!!!!
第四题hard暂时先不考虑了,哈哈,没那个时间去搞呀,哭哭
第五题动态规划。。。。。。。。
第六题找规律。。。。。。。。。
动态规划真不是我现在有时间去看的,找规律也没啥意义呀,算了算了,今天手写了贝叶斯也算是对算法的练习了,今天就做一道简单的medium题吧。。。哭哭
'''
1、丢弃开头空格
2、负号问题
3、无用字符忽略
4、整体无效不转换,输出0
'''
def myAtoi(str):is_null = 0is_lower = 0is_begin = 0s = ''for i in range(len(str)):# 如果遇到了空格if str[i] == ' ':# 如果开始了if is_begin != 0:if s == '-' or s == '':return 0else:return s# 如果没开始if is_begin == 0:#print('aaa')continue# 如果遇到了不是数字的字符if ord(str[i])-48 > 9 or ord(str[i])-48 < 0:#print('bbb')# 如果遇到的是负号if str[i] == '-':# 如果还没开始if is_begin == 0:# 记录是负号is_lower = 1# 开始了is_begin = 1s = s + str[i]# 如果开始了elif is_begin != 0:if s == '-' or s == '':return 0else:return s# 如果遇到的不是负号if str[i] != '-':if s == '-' or s== '':return 0else:return s# 如果遇到了是数字的字符if ord(str[i])-48 >= 0 and ord(str[i])-48 <= 9:s = s + str[i]#print('s:',s)len_s = len(s)if len_s == 0:return 0y = 0if s[0] == '-':global numnum = 0for i in range(len_s - 1):k = len_s - i - 1p = il = 1while p != 0:p = p - 1l = l * 10y += (ord(s[k]) - 48) * lnum = -1*yelse:for i in range(len_s):k = len_s - i - 1p = il = 1while p != 0:p = p - 1l = l * 10y += (ord(s[k]) - 48) * lnum = yif (num < -2147483648):return -2147483648elif (num > 2147483647):return 2147483647return numprint(myAtoi('42'))
print(myAtoi(' -42'))
print(myAtoi('4193 with words'))
print(myAtoi('words and 987'))
print(myAtoi('-91283472332'))
print(myAtoi('""'))
哈哈哈哈,照抄就错了,应该是编译器的问题,我的最后一个案例输出是0,可是leetecode输出竟然是3!!!
惊了!!!
懒得改了,如果有哪位大神知道怎么改,留言给小弟说一下好啦,小弟再ac了它,哈哈哈。
话说leetecode不能使用自定义函数吗?!!!!
一开始的代码感觉写的还不错呀。
'''
1、丢弃开头空格
2、负号问题
3、无用字符忽略
4、整体无效不转换,输出0
'''
def myAtoi(str):is_null = 0is_lower = 0is_begin = 0s = ''for i in range(len(str)):# 如果遇到了空格if str[i] == ' ':# 如果开始了if is_begin != 0:if s == '-' or s == '':return 0else:return s# 如果没开始if is_begin == 0:#print('aaa')continue# 如果遇到了不是数字的字符if ord(str[i])-48 > 9 or ord(str[i])-48 < 0:#print('bbb')# 如果遇到的是负号if str[i] == '-':# 如果还没开始if is_begin == 0:# 记录是负号is_lower = 1# 开始了is_begin = 1s = s + str[i]# 如果开始了elif is_begin != 0:if s == '-' or s == '':return 0else:return s# 如果遇到的不是负号if str[i] != '-':if s == '-' or s== '':return 0else:return s# 如果遇到了是数字的字符if ord(str[i])-48 >= 0 and ord(str[i])-48 <= 9:s = s + str[i]#print('s:',s)num = str_to_int(s)if (num < -2147483648):return -2147483648elif (num > 2147483647):return 2147483647return numdef str_to_int(s):len_s = len(s)if len_s == 0:return 0y = 0if s[0] == '-':for i in range(len_s - 1):k = len_s - i - 1p = il = 1while p!=0:p = p-1l = l * 10y += (ord(s[k])-48)*lreturn -1*yelse:for i in range(len_s):k = len_s - i - 1p = il = 1while p!=0:p = p-1l = l * 10y += (ord(s[k])-48)*lreturn yprint(myAtoi('42'))
print(myAtoi(' -42'))
print(myAtoi('4193 with words'))
print(myAtoi('words and 987'))
print(myAtoi('-91283472332'))
好啦,今天就到这里了,祝大家。额。今天不是什么节日,还是祝大家身体健康,万事如意啦!