Multiple of 3

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.

Note: You can insert the digit anywhere in N 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 = 0i < s.size(); i++)
    {
        sum += s[i] - '0';
    }
    if (sum % 3 == 0)
        return s;
    else
    {
        if (sum % 3 == 1)
        {
            string strstr1;
            int flag = 0;
            for (int i = 0i < s.size(); i++)
            {

                if (s[i] > '2')
                {
                    str = s.substr(i);
                    flag = 1;
                    str1 = s.substr(0i);
                    break;
                }
            }
            if (flag == 1)
            {
                s = "";
                s = str1 + "2" + str;
            }
            else
                s += "2";
        }
        else
        {
            string strstr1;
            int flag = 0;

            for (int i = 0i < s.size(); i++)
            {

                if (s[i] > '1')
                {
                    str = s.substr(i);
                    flag = 1;
                    str1 = s.substr(0i);
                    break;
                }
            }
            if (flag == 1)
            {
                s = "";
                s = str1 + "1" + str;
            }
            else
                s += "1";
        }
        return s;
    }
}
int main()
{

    string s = "5";

    cout << multipleOfThree(s<< "\n";

    return 0;
}


No comments:

Post a Comment