string to int

本文介绍了一种从特定格式的字符串中提取并转换为整数的方法。解析过程包括去除空白字符、判断正负号,并将有效数字组合成整数。若字符串不符合规范,则返回预设值。

problem describe:

  given a string , first find the first word which is not white space;then there will be an optional '+' or '-', but the given the test set the given string will contain more than one symbol or didn't contain any number, if that you should return 0;third,you should find as many  number as possible,and change the string num into int.if the num more than 2^31-1 or smaller than -2^31, you should return 2^31- 1 or  -2^31.

 i.e.

input '+-2'

output '0'

my python solution:

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        slength = len(s)
        full, leave = divmod(slength, (numRows+numRows/2))
        left, right = divmod(leave, numRows)
        returnlist = []
        times = full
        k = 0
        if left == 0:
            left = right
            right =0
        for i in range(numRows):
            if i%2 != 0:
                for colnum in range(times):
                    returnlist[k] = s[i+(3*numRows/2)*times]
                    k += 1
                    if left != 0:
                        if i+(3*numRows/2)*(times+1)<= slength:
                            returnlist[k] = s[i+(3*numRows/2)*(times+1)]
                            k += 1
            else:
                for colnum in range(times):
                    returnlist[k] = s[i+(3*numRows/2)*times]
                    k = k+1
                    returnlist[k] = s[numRows+i/2+ (3*numRows/2)*times]
                    k += 1
                    if left !=0 and i+(3*numRows/2)*(times+1)<slength:
                        returnlist[k] = s[i+(3*numRows/2)*(times+1)]
                        k += 1
                    if right != 0 and numRows+i/2+ (3*numRows/2)*(times+1)<slength:
                        returnlist[k] = s[numRows+i/2+ (3*numRows/2)*(times+1)]
                        k += 1
        need = ''
        for each in returnlist:
            need += each
        return need

 

转载于:https://www.cnblogs.com/whatyouknow123/p/6688488.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值