辣雞劉的Leetcode之旅8【Add Binary,Sqrt(x)】

  1. Add Binary
    題目描述;
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"

簡單描述:二進制相加
代碼如下:

class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        print(bin(int(a,2)+int(b,2))[2:])
        return bin(int(a,2)+int(b,2))[2:]
    
s=Solution()
s.addBinary("1010","1011")

python的函數真他孃的多。
本題中用到的:

bin() 返回一個整數 int 或者長整數 long int 的二進制表示。
示例如下:
>>>bin(10)
'0b1010'
>>> bin(20)
'0b10100'

上面的例子也說明了代碼中爲什麼用到了[2:],就是從第3位開始;
然後讓我們重新認識以下int這個函數:

int(x, base=10)
x -- 字符串或數字。
base -- 進制數,默認十進制。
舉例如下:
>>>int()               # 不傳入參數時,得到結果0
0
>>> int(3)
3
>>> int(3.6)
3
>>> int('12',16)        # 如果是帶參數base的話,12要以字符串的形式進行輸入,12 爲 16進制
18
>>> int('0xa',16)  
10  
>>> int('10',8)  
8

69. Sqrt(x)

題目描述:

Implement int sqrt(int x).

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.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since 
             the decimal part is truncated, 2 is returned.

翻譯:求所給數字的平方根;
我做的第一種方法:

class Solution:
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
		mid=x//2
        if x == 0 or x == 1:
            return x
        for i in range(mid+1):
            if i * i <= x and (i + 1) * (i + 1) > x:
                print(i)
                return i

這種方法在編譯器上可以AC,但是到了LeetCode的平臺就提示:

351 / 1017 test cases passed.
Status: Time Limit Exceeded

也就是說時間複雜度太大了,畢竟是一個一個遍歷。
第二種方法【二分思想】:

class Solution:
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        low,high=0,x
        while low <= high:
            mid = (low + high) / 2
            if mid ** 2 <= x:
                low = mid + 1
            else:
                high = mid - 1
        return low - 1


s=Solution()
s.mySqrt(4)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章