Python
 Computer >> コンピューター >  >> プログラミング >> Python

Pythonの整数から基数3の数値


数値nがあるとすると、この数値に相当する基数3を文字列として見つける必要があります。

したがって、入力が17のような場合、出力は122になります。

これを解決するには、次の手順に従います-

  • n <0の場合:
    • 記号:=-1
  • それ以外の場合は記号:=空白の文字列
  • n:=| n |
  • n <3の場合、
    • nを文字列として返す
  • s:=空白の文字列
  • nは0と同じではありませんが、
    • s:=(n mod 3)連結sの文字列
    • n:=(n / 3)の商
  • return sign concatenate s

理解を深めるために、次の実装を見てみましょう-

class Solution:
   def solve(self, n):
      sign = '-' if n<0 else ''
      n = abs(n)
      if n < 3:
         return str(n)
         s = ''
      while n != 0:
         s = str(n%3) + s
         n = n//3
      return sign+s
ob = Solution()
print(ob.solve(17))

入力

17

出力

122

  1. Pythonのbin()

    bin()関数は、10進数を2進数に変換します。変換するパラメータとして正または負の整数を使用できます。 構文 以下は関数の構文です。 bin(n) Parameters : an integer to convert Return Value : A binary string of an integer or int object. Exceptions : Raises TypeError when a float value is sent as argument. 次の例では、正と負の整数を2進数に変換します。結果には接頭辞0bが付いており、数値が2進表現であることを示しています

  2. 正の整数のビットを逆にするPythonプログラム?

    まず、bin()関数を使用して数値を2進数に変換します。次に、bin()が数値の2進表現のプレフィックスとして0bを追加し、残りの部分を逆にするため、2進表現の最初の2文字をスキップします。また、文字から、左から最後から2番目の文字まで反転します。反転した2進文字列を整数に変換します。 アルゴリズム integernumber(n,bit_size) /* n is the number and bit_size is the bitsize */ Step 1: first convert number into binary . Step 2: skip the first two c