Given a string str, the task is to find the XOR of ASCII values of characters in the string.
Examples:
Input: str = “Geeks”
Output: 95
ASCII value of G = 71
ASCII value of e = 101
ASCII value of e = 101
ASCII value of k = 107
ASCII value of s = 115
XOR of ASCII values = 71 ^ 101 ^ 101 ^ 107 ^ 115 = 95
Input: str = “GfG”
Output: 102
Approach: The idea is to find out the ASCII value of each character one by one and find the XOR value of these values.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int XorAscii(string str, int len)
{
int ans = int (str[0]);
for ( int i = 1; i < len; i++) {
ans = (ans ^ ( int (str[i])));
}
return ans;
}
int main()
{
string str = "geeksforgeeks" ;
int len = str.length();
cout << XorAscii(str, len) << endl;
str = "GfG" ;
len = str.length();
cout << XorAscii(str, len);
return 0;
}
|
Java
class GFG{
static int XorAscii(String str, int len)
{
int ans = (str.charAt( 0 ));
for ( int i = 1 ; i < len; i++) {
ans = (ans ^ ((str.charAt(i))));
}
return ans;
}
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
int len = str.length();
System.out.print(XorAscii(str, len) + "\n" );
str = "GfG" ;
len = str.length();
System.out.print(XorAscii(str, len));
}
}
|
Python3
def XorAscii(str1, len1):
ans = ord (str1[ 0 ])
for i in range ( 1 ,len1):
ans = (ans ^ ( ord (str1[i])))
return ans
str1 = "geeksforgeeks"
len1 = len (str1)
print (XorAscii(str1, len1))
str1 = "GfG"
len1 = len (str1)
print (XorAscii(str1, len1))
|
C#
using System;
class GFG{
static int XorAscii(String str, int len)
{
int ans = (str[0]);
for ( int i = 1; i < len; i++) {
ans = (ans ^ ((str[i])));
}
return ans;
}
public static void Main(String[] args)
{
String str = "geeksforgeeks" ;
int len = str.Length;
Console.Write(XorAscii(str, len) + "\n" );
str = "GfG" ;
len = str.Length;
Console.Write(XorAscii(str, len));
}
}
|
Javascript
<script>
function XorAscii(str, len)
{
let ans = str.codePointAt(0);
for (let i = 1; i < len; i++) {
ans = (ans ^ (str.codePointAt(i)));
}
return ans;
}
let str = "geeksforgeeks" ;
let len = str.length;
document.write(XorAscii(str, len) + "<br>" );
str = "GfG" ;
len = str.length;
document.write(XorAscii(str, len));
</script>
|
Time Complexity: O(N), where N is the length of string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!