Python Program to Replace all 0’s with 1 in a given integer

Replace all 0’s With 1 in given integer

Here we will discuss how to replace all the 0’s with 1 in a given integer.

The concept is simple, find the digits of the integer. Compare each digit with 0 if the digit is equal to 0 then replace it with 1. Construct the new integer with the replaced digits.

  • Example :
    • n=12090 -> 12191
Replace all 0's with 1 in given integer

Implementation:

  • We will convert the integer into string.
  • Then we will convert it into list and then we will traverse through the list.
  • Wherever we find a ‘0’ we will replace with ‘1’.

Python Code:

Replace all 0's with 1

Method 1 :

#taking Input

n=int(input())

#converting into string

n=str(n) 

#then into the list

n=list(n)

r='' #empty string for addind it the item of list

for i in range(len(n)):

    #if we find '0' we will replace it with '1'

    if(n[i]=='0'):

        n[i]='1'

    r=r + n[i]  #creating the new integer 

del n    

print(int(r))

    

Method 2 :

n=int(input("Enter any number"))

s=str(n)

l=[]

for i in s:

    if(i=='0'):

        l.append('1')

    else:

        l.append(i)

ns=""

for i in l:

    ns+=i

print(int(ns))
 
Input:

12090

Output:

12191