123 Number Flip in Python

PythonServer Side ProgrammingProgramming

Suppose we have an integer n, where only 1, 2, and 3 these digits are present. We can flip one digit to a 3. Then find the maximum number we can make.

So, if the input is like 11332, then the output will be 31332

To solve this, we will follow these steps −

  • li := a list by digits of n

  • for x in range 0 to size of li - 1, do

    • if li[x] is not '3', then

      • li[x] := '3'

      • return the number by merging digits from li

  • return n

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, n):
      li = list(str(n))
      for x in range(len(li)):
         if li[x] != '3':
            li[x] = '3'
            return int(''.join(li))
      return n
ob = Solution()
print(ob.solve(11332))

Input

11332

Output

31332
raja
Published on 02-Sep-2020 12:31:04
Advertisements