Uri 1024 – Encryption solution

  • by
uri 1024 Encryption solution

This is a basic string manipulation problem to create a basic encryption program.

First of all, we see from the given inputs that inputs can be a sentence aka. more than one word in an input. So, we can’t use scanf, cin or any other formatted input functions of c/c++ as those will only take input until space is encountered. Instead, we can use getline function.

The first point of the problem is we have to right shift every alphabets 3 positions to the right. Ex: ‘a’ will be ‘d’, ‘b’ will be ‘e’ etc. This is very easy.

All the characters in c have their own integer value. The characters used in C are stored in a table called the ASCII table. And a specific character’s int value is actually the position of that character in the ASCII table. So, we can easily shift to any number of positions by adding that number to that character. Ex: ‘a’ + 3 = ‘d’.

Now, the second point is to reverse the string. Which is very easy. We can use the built-in C++ library function reverse().

Again we have to shift the modified string like before. But we have to only do that with the latter half of the string. Use this formula if the string length is even then half is length/2 else length/2 + 1.

Then do shifting to the truncated/half of the string. This time left shift by 1. So, like the previous step instead of adding 3 just subtract the char by one this time. Remember this time all characters must be shifted, not only alphabets, unlike the first step.
That is all.

#include<iostream>
#include<string>
#include<algorithm>
#include<stdio.h>
using namespace std;
int main() {
    int t_case;
    string x;
    cin >> t_case;
    getchar();
    while(t_case--) {
        getline(cin,x);
        for(int i = 0; i<x.length(); i++) {
            if((x[i]>='A'&& x[i]<='Z')||(x[i]>='a' && x[i]<='z')) {
                x[i] += 3;
            }
        }
        reverse(x.begin(),x.end());
        if(x.length()%2!=0) {
            for(int i = (x.length()-1)/2; i < x.length(); i++) {
                x[i] -=1;
            }
        } else {
            for(int i = x.length()/2; i < x.length(); i++) {
                x[i] -=1;
            }
        }
        cout << x << endl;
    }

    return 0;
}

Click to rate this post!
[Total: 2 Average: 3]
Tags: