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.

题意: 求非负整数的平方根,结果只要保留整数部分(截尾法取整)

正常用法:

>>> import math
>>> math.sqrt(4)
2.0

# 或者:
>>> 4**0.5
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

注:此方法适用于所有非负实数,截尾取整操作略。

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐