Please help me solve the following code in cpp

Anagram Sum

Joey had neatly arranged some words using plastic alphabets corresponding to the integers zero through nine. But as he went to show his project to his dad, he tripped and all his alphabets got jumbled up. Can you find the sum of all the words he had arranged, so he gets an A for effort?

Input Format
The first line contains the jumbled string, S There can be multiple instances of each integer word in S. You can assume are no extra letters in the string.

Output Format
An integer which has the sum of all integers in the jumbled string S.
eg. ans=9(zerooonethreefive=0135=0+1+3+5)

code in cpp

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class AnagramSum {
public static void main(String[] args) {
Scanner scanner = new Scanner(;
String s = scanner.nextLine();

    Map<Character, Integer> charToNum = createCharToNumMapping();

    int sum = 0;
    for (char c : s.toCharArray()) {
        if (charToNum.containsKey(c)) {
            sum += charToNum.get(c);

    System.out.println("Sum of the integers in the jumbled string: " + sum);

private static Map<Character, Integer> createCharToNumMapping() {
    Map<Character, Integer> charToNum = new HashMap<>();
    charToNum.put('z', 0);
    charToNum.put('o', 1);
    charToNum.put('t', 2);
    charToNum.put('h', 3);
    charToNum.put('f', 4);
    charToNum.put('i', 5);
    charToNum.put('s', 6);
    charToNum.put('e', 7);
    charToNum.put('g', 8);
    charToNum.put('n', 9);
    return charToNum;


1 Like

can you please provide the code in cpp or explain how the code works exactly

include <unordered_map>

using namespace std;

int main() {
string s;
cin >> s;

// Mapping each word to its corresponding integer
unordered_map<char, int> wordToInteger = {
    {'z', 0},
    {'e', 1},
    {'o', 2},
    {'h', 3},
    {'r', 4},
    {'f', 5},
    {'x', 6},
    {'s', 7},
    {'g', 8},
    {'n', 9}

int sum = 0;

// Calculating the sum of integers in the jumbled string
for (char c : s) {
    sum += wordToInteger[c];

cout << "Sum: " << sum << endl;

return 0;