python另外2位数字

ale*_*mon 2 python binary

我正在研究算法.练习包括放置2位数(10到99之间),然后添加两位数.我在python中创建它并且它可以工作,但是我的老师说有另一种方法可以在没有我正在使用的转换的情况下完成它.你能帮助我吗?有没有更好的办法?谢谢.

for i in range(5):
    add = 0
    num = input("Number: ")
    num = int(num)
    if num > 9 and num < 100:
        num = str(num)
        add = int(num[0]) + int(num[1])
        print("The addition of the two digits is: " + str(add))
    else:
        print("It is not a two digit number.")
Run Code Online (Sandbox Code Playgroud)

Jun*_*sor 6

我认为他的意思是:

(num // 10) + (num % 10)
Run Code Online (Sandbox Code Playgroud)

随着num // 10您执行整数除法与10但是,这是第一位.随着num % 10你得到分区的剩余部分,这是第二个数字.例如:

>>> 67 // 10
6
>>> 67 % 10
7
Run Code Online (Sandbox Code Playgroud)

最简洁的方法必须是:

sum(divmod(num, 10))
Run Code Online (Sandbox Code Playgroud)

因为divmod用10执行整数除法并同时找到余数.所以sum我们得到这两个数字的总和.例如:

>>> divmod(67, 10)
(6, 7)
>>> sum(divmod(67, 10))
13
Run Code Online (Sandbox Code Playgroud)

  • 当然不是.成为一名优秀的程序员是一个过程,一个非常好的因素是尝试自己解决问题.如果我们不允许自己研究其他做法,那就错了. (2认同)