Reverse Integer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import sys

class Solution1:
def reverse(self, x: int) -> int:
# 新增临时变量存储反转结果
reversed_signed_x = 0
if x < 0:
num = -x
else:
num = x
# 反转整数
while num > 0:
reversed_signed_x = reversed_signed_x * 10 + num % 10
num //= 10
if x < 0:
reversed_signed_x = -reversed_signed_x
# 判定结果值是否在规定范围内
if reversed_signed_x < -2 ** 31 or reversed_signed_x > 2 ** 31 - 1:
return 0
return reversed_signed_x

class Solution2:
def reverse(self, x: int) -> int:
# 对传入整型参数加绝对值再转化为字符串使用[::-1]反转,再转化成无符号整数
reversed_signed_x = int(str(abs(x))[::-1])
# 若原值小于0,对无符号整数做负数处理
if x < 0:
reversed_signed_x = -reversed_signed_x
# 判定结果值是否在规定范围内
if reversed_signed_x < -2 ** 31 or reversed_signed_x > 2 ** 31 - 1:
return 0
return reversed_signed_x

s1 = Solution1()
s2 = Solution2()
while True:
try:
x = int(input("An integer please: "))
except ValueError:
print("Input is not an integer!")
sys.exit()
print(s1.reverse(x), s2.reverse(x))

Count Number of Distinct Integers After Reverse Operations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from collections import defaultdict
from typing import List
import sys

class Solution1:
def countDistinctIntegers(self, nums: List[int]) -> int:
res = []
for item in nums:
res.append(int(str(item)[::-1]))
nums.extend(res)
return len(set(nums))

class Solution2:
def countDistinctIntegers(self, nums: List[int]) -> int:
dict_nums = defaultdict(int)
for item in nums:
if item in dict_nums:
continue
dict_nums[item] = 1
for item in nums:
reversed_positive_item = int(str(item)[::-1])
if reversed_positive_item not in dict_nums:
dict_nums[reversed_positive_item] = 1
return len(dict_nums)

s1 = Solution1()
s2 = Solution2()
while True:
try:
nums = list(map(int, input("An integer please: ").split()))
for item in nums:
if item < 0:
raise ValueError
except ValueError:
print("Input is not a positive integer!")
sys.exit()
print(s1.countDistinctIntegers(nums), s2.countDistinctIntegers(nums))

Number of Provinces

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
from typing import List
import sys

class Solution1:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
visited = set()

def dfs(item):
visited.add(item)
for item1 in range(len(isConnected)):
if isConnected[item][item1] and item1 not in visited:
dfs(item1)

number_of_circles = 0
for item in range(len(isConnected)):
if item not in visited:
number_of_circles += 1
dfs(item)

return number_of_circles

class DSU:
def __init__(self, length):
self.par = list(range(length))
self.rank = [1] * length
self.size = 1

def find(self, u):
if u != self.par[u]:
self.par[u] = self.find(self.par[u])
return self.par[u]

def union(self, u, v):
uu, vv = self.find(u), self.find(v)
if uu == vv:
return False
if self.rank[uu] > self.rank[vv]:
self.par[vv] = uu
elif self.rank[vv] > self.rank[uu]:
self.par[uu] = vv
else:
self.par[uu] = vv
self.rank[vv] += 1
self.size += 1
return True

class Solution2:

def isConnected(self, u, v, isConnected):
return isConnected[u][v] == 1

def findCircleNum(self, isConnected: List[List[int]]) -> int:
length_isConnected = len(isConnected)
union_find = DSU(length_isConnected)
if not isConnected:
return 0
for u in range(length_isConnected):
for v in range(u, length_isConnected):
if self.isConnected(u, v, isConnected):
union_find.union(u, v)
return len(set([union_find.find(i) for i in range(length_isConnected)]))

s1 = Solution1()
s2 = Solution2()

while True:
try:
rows = int(input("Rows: "))
cols = int(input("Columns: "))
matrix = []
for i in range(rows):
row_input = input(f'Elements in row {i + 1}: ')
row = list(map(int, row_input.split()))
matrix.append(row)
for row in range(len(matrix)):
for col in range(len(matrix[0])):
if matrix[row][col] != 0 and matrix[row][col] != 1:
raise ValueError
except ValueError:
print("Input is not a 0 1 matrix")
sys.exit()
print(s1.findCircleNum(matrix), s2.findCircleNum(matrix))