Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

HackerEarth Multiple of 3 problem solution

YASH PAL, 31 July 2024
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)
coding problems

Post navigation

Previous post
Next post
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
  • Hackerrank Day 14 scope 30 days of code solution
©2025 Programming101 | WordPress Theme by SuperbThemes