You are given an integer and your task is to make a multiple of 3. In order to make multiple of 3, you can insert at most one digit in .
Your task is to find the minimum possible which is a multiple of 3 after inserting at most one digit.
Note: You can insert the digit anywhere in and also you need not necessarily insert.
Example:
Input: s = 5
Output: 15
Approach
C++
#include <bits/stdc++.h>using namespace std;string multipleOfThree(string s){int sum = 0;for (int i = 0; i < s.size(); i++){sum += s[i] - '0';}if (sum % 3 == 0)return s;else{if (sum % 3 == 1){string str, str1;int flag = 0;for (int i = 0; i < s.size(); i++){if (s[i] > '2'){str = s.substr(i);flag = 1;str1 = s.substr(0, i);break;}}if (flag == 1){s = "";s = str1 + "2" + str;}elses += "2";}else{string str, str1;int flag = 0;for (int i = 0; i < s.size(); i++){if (s[i] > '1'){str = s.substr(i);flag = 1;str1 = s.substr(0, i);break;}}if (flag == 1){s = "";s = str1 + "1" + str;}elses += "1";}return s;}}int main(){string s = "5";cout << multipleOfThree(s) << "\n";return 0;}
No comments:
Post a Comment