1
0

More than 3 years have passed since last update.

LeetCord(記録)python3

Posted at

1. Two Sum

nums = [2,7,11,15]
target = 9
result = []
for i in range(len(nums)):
  for j in range(i,len(nums)):
    if nums[i] + nums[j] == target:
      result = [i, j]
      break;

print(result)

7. Reverse Integer

符号付き32ビット整数xが与えられた場合、桁を逆にしてxを返します。 xを逆にすると、値が符号付き32ビット整数の範囲[-231、231-1]の外に出る場合は、0を返します。

環境では64ビット整数(符号付きまたは符号なし)を格納できないと想定します。

x = 123

s = (x > 0) - (x < 0) #1(true)-0(false)
r = int(str(x*s)[::-1])
y = s*r * (r < 2**31) #321*1(true)

print (s)#1
print (r)#321
print (y)#321

範囲を全指定にしてマイナスステップにすると、要素がリバースする。

>>> a[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]

True, False に四則演算を適用すると

True は 1、False は 0 として扱われます。

(x > 0) - (x < 0) #1か0を返す
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0