1290. 二進制鏈表轉整數
難度:簡單
給你一個單鏈表的引用結點 head。鏈表中每個結點的值不是 0 就是 1。已知此鏈表是一個整數數字的二進制表示形式。
請你返回該鏈表所表示數字的 十進制值 。
示例 1:
輸入:head = [1,0,1]
輸出:5
解釋:二進制數 (101) 轉化爲十進制數 (5)
示例 2:
輸入:head = [0]
輸出:0
示例 3:
輸入:head = [1]
輸出:1
示例 4:
輸入:head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
輸出:18880
示例 5:
輸入:head = [0,0]
輸出:0
提示:
- 鏈表不爲空。
- 鏈表的結點總數不超過 30。
- 每個結點的值不是 0 就是 1。
解決方案 1:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
string = ''
while head is not None:
string += str(head.val)
head = head.next
lenth = len(string)
ans = 0
for i in string:
lenth -= 1
ans += int(i) * pow(2, lenth)
return ans
執行用時 | 內存消耗 | 語言 |
---|---|---|
48 ms | 13.8 MB | Python3 |
解決方案 2:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
string = ''
while head is not None:
string += str(head.val)
head = head.next
return int(string, 2)
-
知識點:
python輸出二進制/十進制/十六進制的整數
int('101', 2) int('101', 10) int('101', 16)
1291. 順次數
難度:中等
我們定義「順次數」爲:每一位上的數字都比前一位上的數字大 1 的整數。
請你返回由 [low, high] 範圍內所有順次數組成的 有序 列表(從小到大排序)。
示例 1:
輸出:low = 100, high = 300
輸出:[123,234]
示例 2:
輸出:low = 1000, high = 13000
輸出:[1234,2345,3456,4567,5678,6789,12345]
提示:
- 10 <= low <= high <= 10^9
解決方案:
class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
s = '123456789'
res = list()
small = len(str(low))
big = len(str(high))
while small <= big:
idx = 0
while idx + small <= len(s):
digit = int(s[idx:idx+small])
if digit >= low and digit <= high:
res.append(digit)
idx += 1
small += 1
return res
1292. 元素和小於等於閾值的正方形的最大邊長
難度:中等
給你一個大小爲 m x n 的矩陣 mat 和一個整數閾值 threshold。
請你返回元素總和小於或等於閾值的正方形區域的最大邊長;如果沒有這樣的正方形區域,則返回 0 。
示例 1:
輸入:mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4
輸出:2
解釋:總和小於 4 的正方形的最大邊長爲 2,如圖所示。
示例 2:
輸入:mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1
輸出:0
示例 3:
輸入:mat = [[1,1,1,1],[1,0,0,0],[1,0,0,0],[1,0,0,0]], threshold = 6
輸出:3
示例 4:
輸入:mat = [[18,70],[61,1],[25,85],[14,40],[11,96],[97,96],[63,45]], threshold = 40184
輸出:2
提示:
- 1 <= m, n <= 300
- m == mat.length
- n == mat[i].length
- 0 <= mat[i][j] <= 10000
- 0 <= threshold <= 10^5
解決方案1: