Find letter’s position in Alphabet using Bit operation
Last Updated :
26 Nov, 2021
Given a string of English alphabets. The task is, for every character in the string print its position in the English alphabets.
Note: The characters in the string are considered to be case-insensitive. That is, both ‘A’ and ‘a’ is at the first position.
Examples:
Input: “Geeks”
Output: 7 5 5 11 19
‘G’ is the 7th character of the alphabets
‘e’ is the 5th and so on…
Input: “Algorithms”
Output: 1 12 7 15 18 9 20 8 13 19
Approach:
A letter’s position in Alphabet can easily be found by performing logical AND operation with the number 31.
Note that this is only applicable to letters and not special characters.
Every letter has an ASCII value which can be represented in binary form. Performing the bitwise and of this value with the number 31 will give the letter’s position in the alphabets.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
const int NUM = 31;
void positions(string str, int n)
{
for ( int i = 0; i < n; i++) {
cout << (str[i] & NUM) << " " ;
}
}
int main()
{
string str = "Geeks" ;
int n = str.length();
positions(str, n);
return 0;
}
|
Java
public class GFG {
public static final int NUM = 31 ;
static void positions(String str, int n)
{
for ( int i = 0 ; i < n; i++) {
System.out.print((str.charAt(i) & NUM) + " " );
}
}
public static void main(String[] args)
{
String str = "Geeks" ;
int n = str.length();
positions(str, n);
}
}
|
Python
NUM = 31
def positions( str ):
for i in str :
print (( ord (i) & NUM), end = " " )
str = "Geeks"
positions( str )
|
C#
using System;
class GFG {
public static int NUM = 31;
static void positions( string str, int n)
{
for ( int i = 0; i < n; i++) {
Console.Write((str[i] & NUM) + " " );
}
}
public static void Main()
{
string str = "Geeks" ;
int n = str.Length;
positions(str, n);
}
}
|
PHP
<?php
function positions( $str , $n )
{
$a = 31;
for ( $i = 0; $i < $n ; $i ++)
{
print ((ord( $str [ $i ])&( $a )). " " );
}
}
$str = "Geeks" ;
$n = strlen ( $str );
positions( $str , $n );
?>
|
Javascript
<script>
const NUM = 31;
function positions(str, n)
{
for (i = 0; i < n; i++)
{
document.write((str[i].charCodeAt(0) & NUM) +
" " );
}
}
var str = "Geeks" ;
var n = str.length;
positions(str, n);
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...