Table of Contents
Example
illustrate
method
Output
in conclusion
Home Backend Development C++ encrypted string

encrypted string

Sep 08, 2023 am 10:37 AM
programming string encryption

encrypted string

Encryption is a technique that changes data by using certain techniques or certain steps so that it changes to another kind of information or from which the previous information cannot be directly collected. For encryption, we have to follow certain steps that are fixed for the specific encryption type.

In this question we will get a string and we have to encrypt it by following the given steps -

  • First we have to get all substrings that contain the same character and replace that substring with a single character followed by the length of the substring.

  • Now, change the length to a hexadecimal value and all characters of the hexadecimal value must be changed to lowercase.

  • Finally, reverse the entire string.

Example

Input 1: string str = "aabbbcccc"
Copy after login
Output: "4c3b2a"
Copy after login

illustrate

First, we will get all the substrings that contain the same number of characters and replace them with the frequency of the characters, which will give us the string "a2b3c4". Now we change the length to a hexadecimal value, but 2, 3 and 4 have the same value in hexadecimal form. Finally we reverse the string and the end result will be 4c3b2a.

Input2: string str = "oooooooooooo"
Copy after login
Output: "co"
Copy after login

illustrate

First, we convert the string into the frequency string "o12". Now, the hexadecimal value of 12 is C, we change it to lowercase i.e. c and replace it into the string and then reverse the string.

method

From the above example, we have an idea about the problem, now let us enter the implementation part -

  • In implementation, first, we will implement a function that takes input as an integer and returns a string as the return value.

  • This function will be used to convert the given integer to a hexadecimal value, with one modification, using lowercase English letters instead of uppercase English characters.

  • We will define another function in which we will use a for loop to iterate through the string and then for the substring of the same character we will use a while loop until we find a character that is equal to the current character .

  • We will calculate the frequency and change it to a hexadecimal value and add it to the string with the current index character.

  • Finally, we reverse the string and return it to the main function for printing.

Example

#include <bits/stdc++.h>
using namespace std;
// function to convert the integer to hexadecimal values 
string convertToHexa(int val){
   string res = ""; // string to store the result     
   while(val != 0){
      int cur = val %16; // getting the mode of the current value         
      if(cur < 10){
         res += '0' + cur;
       }
      else{
         res += 87 + cur; // adding 87 to get the lowercase letters 
      }
      val /= 16; // updating the current value 
   }
   return res;
}

// function to encrypt the string 
string encrypt(string str){
   int len = str.length(); // getting the length of the string 
   int freq = 0; // variable to store the frequency 
   string ans = ""; // string to store the answer    
   
   // traversing over the string 
   for(int i=0; i<len; i++){
      int j = i; // variable to keep track the substring with the same character
      while(j < len && str[j] == str[i]){
         j++;
      }
      freq = j-i;
      ans += str[i];
      
      // calling the function to get the hexadecimal value 
      string hexaValue = convertToHexa(freq);
      ans += hexaValue;        
      i = j-1;
   } 
   
   // reversing the string 
   reverse(ans.begin(), ans.end());
   return ans;
}

// main function 
int main(){
   string str = "aaabbbbccccccccccc"; // given string  
   
   // calling the function to get the encrypted string
   cout<<"The given string after the encryption is: "<<encrypt(str)<<endl;
   return 0;
}
Copy after login

Output

The given string after the encryption is: bc4b3a
Copy after login

Time and Space Complexity

The time complexity of the above code is O(N), where N is the size of the given string. It took us N time to iterate over the string, while reversing the string took less than N time.

The space complexity of the above code to store the final string is O(N), if we ignore this, no extra space will be used.

Notice

Encryption can be done in an infinite number of ways, and is only concerned with defining the rules to encrypt the keys. The main characteristic of encryption is that it must give the same result every time for the same input.

in conclusion

In this tutorial, we implemented a code that encrypts a given string according to rules. First, we have to get substrings containing elements of the same type and replace them with characters and their frequencies. Next, we change the frequency to a hexadecimal number and finally reverse the entire string. The time complexity of the above code is O(N).

The above is the detailed content of encrypted string. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is programming for and what is the use of learning it? What is programming for and what is the use of learning it? Apr 28, 2024 pm 01:34 PM

1. Programming can be used to develop various software and applications, including websites, mobile applications, games, and data analysis tools. Its application fields are very wide, covering almost all industries, including scientific research, health care, finance, education, entertainment, etc. 2. Learning programming can help us improve our problem-solving skills and logical thinking skills. During programming, we need to analyze and understand problems, find solutions, and translate them into code. This way of thinking can cultivate our analytical and abstract abilities and improve our ability to solve practical problems.

Collection of C++ programming puzzles: stimulate thinking and improve programming skills Collection of C++ programming puzzles: stimulate thinking and improve programming skills Jun 01, 2024 pm 10:26 PM

C++ programming puzzles cover algorithm and data structure concepts such as Fibonacci sequence, factorial, Hamming distance, maximum and minimum values ​​of arrays, etc. By solving these puzzles, you can consolidate C++ knowledge and improve algorithm understanding and programming skills.

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Get the gate.io installation package for free Get the gate.io installation package for free Feb 21, 2025 pm 08:21 PM

Gate.io is a popular cryptocurrency exchange that users can use by downloading its installation package and installing it on their devices. The steps to obtain the installation package are as follows: Visit the official website of Gate.io, click "Download", select the corresponding operating system (Windows, Mac or Linux), and download the installation package to your computer. It is recommended to temporarily disable antivirus software or firewall during installation to ensure smooth installation. After completion, the user needs to create a Gate.io account to start using it.

Demystifying C: A Clear and Simple Path for New Programmers Demystifying C: A Clear and Simple Path for New Programmers Oct 11, 2024 pm 10:47 PM

C is an ideal choice for beginners to learn system programming. It contains the following components: header files, functions and main functions. A simple C program that can print "HelloWorld" needs a header file containing the standard input/output function declaration and uses the printf function in the main function to print. C programs can be compiled and run by using the GCC compiler. After you master the basics, you can move on to topics such as data types, functions, arrays, and file handling to become a proficient C programmer.

Unleash Your Inner Programmer: C for Absolute Beginners Unleash Your Inner Programmer: C for Absolute Beginners Oct 11, 2024 pm 03:50 PM

C is an ideal language for beginners to learn programming, and its advantages include efficiency, versatility, and portability. Learning C language requires: Installing a C compiler (such as MinGW or Cygwin) Understanding variables, data types, conditional statements and loop statements Writing the first program containing the main function and printf() function Practicing through practical cases (such as calculating averages) C language knowledge

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles