- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# C++ code to find the number of dial rotations to print a string

Suppose, we are given a rotary dial that contains all lowercase English alphabets. There is a printer attached to the dial and whichever character resides in the pointer of the rotary dial for 3 seconds, gets printed. The rotary dial initially stays at the letter 'a' and it does not reset to the initial position whenever it prints a character. We are given a string s and we have to print the given string. Whenever we move the dial to another letter, one amount of rotation takes place. We have to find out the total amount of rotations needed to print the given string 's'.

So, if the input is like s = "elephant", then the output will be 63.

## Steps

To solve this, we will follow these steps −

t := 'a' res := 0 for initialize i := 0, when i < size of s, update (increase i by 1), do: res := res + minimum of (|t - s[i]|, 26 - |t - s[i]|) t := s[i] return res

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h> using namespace std; #define N 100 int solve(string s) { char t = 'a'; int res = 0; for(int i = 0; i < s.size(); i++){ res += min(abs(t - s[i]), 26 - abs(t - s[i])); t = s[i]; } return res; } int main() { string s = "elephant"; cout<< solve(s); return 0; }

## Input

"elephant"

## Output

63

- Related Questions & Answers
- C++ code to find the number of scans needed to find an object
- C++ code to find the number of refill packs to be bought
- C++ code to find out number of battery combos
- Minimum rotations required to get the same string in C++
- All combinations of strings that can be used to dial a number in C/C++?
- C++ code to count number of even substrings of numeric string
- C++ Program to Find the Number of Permutations of a Given String
- C++ code to find reduced direction string of robot movement
- Find the Number of Substrings of a String using C++
- PHP program to find the number of characters in the string
- C++ code to find total number of digits in special numbers
- C++ code to find string where trygub is not a substring
- C++ code to count number of weight splits of a number n
- C++ code to find number to disprove given prime hypothesis
- C++ code to find minimum correct string from given binary string