Goodspeed

导航

模拟二进制实现减法

#! /usr/bin/python
# coding=utf-8
import math
def main(x,y):
    #对减数取反
    x, y = bin(x)[2:], bin(y)[2:]
    l = max([len(x),len(y)]) #最大长度
    #对y取反
    y = "1" * (l - len(y)) + "".join(['1' if i == '0' else '0' for i in y])
    x,y = int(x,2), int(y,2)
    z = x + y + 1
    z = bin(z)
    #拿掉最高位
    z = z[3:]
    return int(z,2)
        
if __name__ == '__main__':
    import unittest,random
    class cacheTest(unittest.TestCase):
        def test_img(self):
            for i in range(0,100000):
                x, y = random.randint(1, 1000),random.randint(1, 1000)
                if x < y : x,y = y,x
                self.assertEqual(main(x, y), x - y)
    unittest.main()
    
    

  

posted on 2012-11-30 14:18  Goodspeed  阅读(269)  评论(0编辑  收藏  举报