
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Replace All Zeros with One in a Given Integer
Problem
Write a program to replace all zeros (0's) with 1 in a given integer.
Given an integer as an input, all the 0's in the number has to be replaced with 1.
Solution
Consider an example given below −
Here, the input is 102410 and the output is 112411.
Algorithm
Refer an algorithm given below to replace all the 0’s to 1 in an integer.
Step 1 − Input the integer from the user.
Step 2 − Traverse the integer digit by digit.
Step 3 − If a '0' is encountered, replace it by '1'.
Step 4 − Print the integer.
Example
Given below is the C program to replace all 0's with 1 in a given integer −
#include<stdio.h> int replace(long int number){ if (number == 0) return 0; //check last digit and change it if needed int digit = number % 10; if (digit == 0) digit = 1; // Convert remaining digits and append to its last digit return replace(number/10) * 10 + digit; } int Convert(long int number){ if (number == 0) return 1; else return replace(number); } int main(){ long int number; printf("
Enter any number : "); scanf("%d", &number); printf("
After replacement the number is : %dn", Convert(number)); return 0; }
Output
When the above program is executed, it produces the following output −
Enter any number: 1056110010 After replacement the number is: 1156111111
Advertisements