In this HackerEarth Multiple of 3 problem solution, You are given an integer N and your task is to make N a multiple of 3. In order to make N multiple of 3, you can insert at most one digit in N.

Your task is to find the minimum possible N which is a multiple of 3 after inserting at most one digit.


HackerEarth Multiple of 3 problem solution


HackerEarth Multiple of 3 problem solution.

#include<bits/stdc++.h>
using namespace std;
#define FIO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define mod 1000000007
#define endl "\n"
#define test ll t; cin>>t; while(t--)
typedef long long int ll;
void solve(){
string s; cin>>s;
int n=(int)s.length();
int sum=0;
for(int i=0;i<n;i++){
sum+=(s[i]-'0');
}
sum%=3;
if(sum==0){
cout<<s<<endl; return;
}
bool ok=false;
int dig=3-sum;
for(int i=0;i<n;i++){
if(!ok && s[i]-'0'>dig){
cout<<dig; ok=true;
}
cout<<s[i];
}
if(!ok) cout<<dig;
cout<<endl;
}
int main() {
FIO;
test
{
solve();
}
return 0;
}

Second solution

t = int(input())
while t > 0:
t -= 1
n = int(input())
d = n % 3
if d == 0:
print(n)
continue
d = str(3 - d)
n = str(n)
mn = int(d + n)
for i in range(len(n)):
mn = min(mn, int(n[:i + 1] + d + n[i + 1:]))
print(mn)