
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Largest even number possible by using one swap operation in given number in C++
In this tutorial, we are going to write a program that finds the largest possible even number with a single swap of digits.
Let's see the steps to solve the problem.
- Initialise the number in string format.
- Iterate over the given number.
- Find the even digit that is less than or equal to the last digit of the number.
- Break the loop if you find the desired even digit.
- If the even digit doesn't exist, then return the given number.
- Swap the last digit with the even digit you found in the above step.
- Return the number
Example
#include <bits/stdc++.h> using namespace std; string getLargestEvenNumber(string number, int n) { int even = INT_MAX, index; for (int i = 0; i < n - 1; i++) { if ((number[i] - '0') % 2 == 0) { even = (number[i] - '0'); index = i; } if (even <= (number[n - 1] - '0')) { break; } } if (even == INT_MAX) { return number; } swap(number[index], number[n - 1]); return number; } int main() { string number = "15433"; cout << getLargestEvenNumber(number, 5) << endl; return 0; }
Output
If you run the above code, then you will get the following result.
15334
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
- Related Articles
- Largest smaller number possible using only one swap operation in C++
- Form the largest number using at most one swap operation C++
- Next higher number using atmost one swap operation in C++
- Largest number with one swap allowed in C++
- Form the smallest number using at most one swap operation in C++
- Python - Largest number possible from list of given numbers
- Finding the maximum number using at most one swap in JavaScript
- Largest N digit number divisible by given three numbers in C++
- Largest even digit number not greater than N in C++
- Golang Program to Print the Largest Even and Largest Odd Number in a List
- Largest Number By Two Times in Python
- Program to reduce list by given operation and find smallest remaining number in Python
- Haskell Program to check the given number is an EVEN number using library function
- Average of even numbers till a given even number?
- Find the largest number in a series by using pointers in C language

Advertisements