How to find the max absolute difference between consecutive characters in a string with C++

2 Answers

0 votes
#include <iostream>
#include <string>
#include <cmath>

int maxAsciiDiff(const std::string& s) {
    if (s.size() < 2) return 0;  // No consecutive characters

    int maxDiff = 0;

    for (size_t i = 0; i < s.size() - 1; ++i) {
        int diff = abs(s[i] - s[i + 1]);
        if (diff > maxDiff) {
            maxDiff = diff;
        }
    }

    return maxDiff;
}

int main() {
    std::string s = "jumplings";
    
    std::cout << "Maximum ASCII difference: " << maxAsciiDiff(s) << std::endl;
}



/*
run:

Maximum ASCII difference: 12

*/

 



answered Jan 9 by avibootz
0 votes
#include <iostream>
#include <string>
#include <cmath>

int maxAsciiDiff(const std::string& s, char &c1, char &c2) {
    if (s.size() < 2) return 0;  // No consecutive characters

    int maxDiff = 0;

    for (size_t i = 0; i < s.size() - 1; ++i) {
        int diff = abs(s[i] - s[i + 1]);
        if (diff > maxDiff) {
            maxDiff = diff;
            c1 = s[i];
            c2 = s[i + 1];
        }
    }

    return maxDiff;
}

int main() {
    std::string s = "jumplings";

    char a = '\0', b = '\0';
    int result = maxAsciiDiff(s, a, b);

    std::cout << "Maximum ASCII difference: " << result << std::endl;
    std::cout << "Characters: '" << a << "' and '" << b << "'" << std::endl;
}


/*
run:

Maximum ASCII difference: 12
Characters: 'g' and 's'

*/

 



answered Jan 9 by avibootz
...