はじめに
ポイント
- for文とif文を使う
この記事で得られること
- for文の基本的な使い方
- if文の基本的な使い方
この記事が役立ちそうな方
- Pythonの初心者
- プログラミング初心者
- for文やif文の使い方を練習したい方
詳細
問題
原文
There is a function
signFunc(x)
that returns:
1
ifx
is positive.-1
ifx
is negative.0
ifx
is equal to0
.You are given an integer array
nums
. Letproduct
be the product of all values in the arraynums
.Return
signFunc(product)
.
Example 1:
123 Input: nums = [-1,-2,-3,-4,3,2,1]Output: 1Explanation: The product of all values in the array is 144, and signFunc(144) = 1Example 2:
123 Input: nums = [1,5,0,2,-3]Output: 0Explanation: The product of all values in the array is 0, and signFunc(0) = 0Example 3:
123 Input: nums = [-1,1,-1,1,-1]Output: -1Explanation: The product of all values in the array is -1, and signFunc(-1) = -1
Constraints:
1 <= nums.length <= 1000
-100 <= nums[i] <= 100
内容(和訳)
signFunc(x)という関数があります。
この関数はxが正数なら1、xが負数なら-1、xが0なら0を返します。
整数配列numsが与えられます。
変数productに配列numsの全要素の掛算の結果を保持し、signFunc(product)を返してください。
※正しくない可能性があります。
解答
解答1:Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class Solution: def arraySign(self, nums: List[int]) -> int: #総積を保持する変数 product = 1 #numsの全ての要素を掛算する for i in nums: product *= i #掛算の結果が0よりも大きければ if product > 0: #1を返す return 1 #0未満であれば elif product < 0: #-1を返す return -1 #0なら else: #0を返す return 0 |
終わりに
補足・参考・感想
問題を分類しました。テーマごとに集中して問題を解くことができます。
LeeetCodeの問題をアルゴリズムとデータ構造による分類
LeetCodeに特有の内容など、知っておくと役に立つかもしれないことをまとめました。
疑問が解決した方はこちらへ
次:1502. Can Make Arithmetic Progression From Sequence
疑問が解決しない方はこちらへ
if文の基本的な使い方をおさらいしたい方はこの記事へどうぞ
for文の基本的な使い方をおさらいしたい方はこの記事へどうぞ
コメント