- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find maximum number by adding 5 at any place in Python
Suppose we have a number n, we have to find the maximum number we can get by inserting 5 anywhere in the number.
So, if the input is like n = 834, then the output will be 8534.
To solve this, we will follow these steps −
if n > 0, then
s := n as string
k := blank string
c := False
for each character i in s, do
if i < 5 and c is False, then
k := k concatenate "5" concatenate i
c := True
otherwise,
k := k concatenate i
return k as integer
otherwise,
k := blank string
s := |n| as string
c := False
for each character i in s, do
if i > 5 and c is same as False, then
k := k concatenate "5" concatenate i
c := True
otherwise,
k := k concatenate i
if c is false, then
k := k concatenate "5"
return (-k)
Example
Let us see the following implementation to get better understanding
def solve(n): if n > 0: s = str(n) k = "" c = False for i in s: if int(i) < 5 and c == False: k += "5" + i c = True else: k += i return int(k) else: k = "" s = str(abs(n)) c = False for i in s: if int(i) > 5 and c == False: k += "5" + i c = True else: k += i if not c: k += "5" return int("-" + k) n = 834 print(solve(n))
Input
834
Output
8534
Advertisements