Add Binary
Given two binary strings, return their sum (also a binary string). [#67]
The input strings are both non-empty and contains only characters 1 or 0 .
Examples: Input: a = "11", b = "1" Output: "100" Input: a = "1010", b = "1011" Output: "10101"
题意: 给定两个二进制数字符串,求两者之和的二进制数字符串。
>>> binsum = lambda a,b : bin(int(a,2)+int(b,2))[2:] >>> a = "1010"; b = "1011" >>> binsum(a,b) '10101' >>> a = "11"; b = "1" >>> binsum(a,b) '100' >>>
Sqrt(x)
Implement int sqrt(int x) . [#69]
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Examples: Input: 4 Output: 2 Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
题意: 求非负整数的平方根,结果只要保留整数部分(截尾法取整)
正常用法:
1. >>> import math 2. >>> math.sqrt(4) 3. 2.0 4. 5. # 或者: 6. >>> 4**0.5 7. 2.0
牛顿迭代法:
>>> def Sqrt1(x): r = x while r*r>x: r = (r+x/r)/2 return r >>> Sqrt1(9) 3.0 >>> Sqrt1(3) 1.7320508075688772 >>> Sqrt1(2) 1.414213562373095 >>> Sqrt1(1.44) 1.2 >>> Sqrt1(0) 0
注:此方法适用于所有非负实数,截尾取整操作略。