判断字符是否唯一,位移运算符出错提示ValueError: negative shift count

博客探讨了在处理字符唯一性问题时遇到的'negative shift count'错误,该错误源于使用位移运算符不当。文章指出,错误可能因大写英文字母输入引起,并建议参考LeetCode官方解题思路,特别是注意ord()函数的使用和字符编码的位移计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码参考Leetcode 面试题01.01 字符是否唯一的解题思路
def sss():
    s = input('请输入字符')
    mark = 0
    for i in s:
        move_bit = ord(i) - ord('a')
        if(mark & (1 << move_bit)) != 0:
            print('F')
            return False
        else:
            mark |= 1 << move_bit
    print('T')
    return True




# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    sss()
请输入字符LEETCODE



---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-1-e57e25f349dd> in <module>
     17 # Press the green button in the gutter to run the script.
     18 if __name__ == '__main__':
---> 19     sss()


<ipython-input-1-e57e25f349dd> in sss()
      4     for i in s:
      5         move_bit = ord(i) - ord('a')
----> 6         if(mark & (1 << move_bit)) != 0:
      7             print('F')
      8             return False


ValueError: negative shift count

提示出了negative shift count错误,是因为输入了大写英文字母

ord('L') - ord('a')
-21
1 << -21
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-3-d7e69202dc2f> in <module>
----> 1 1 << -21


ValueError: negative shift count

是因为出现了位移运算符的错误,才会提示negative shift count
需要注意的是,ord(‘c’)-ord(‘a’)=2,所以将其左移两位,具体思路可参考leetcode官网解题思路

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值