Given string str, the task is to check the sum of ASCII values of all characters in this string is a perfect cube or not.
Examples :
Input: str = “ll”
Output: Yes
ASCII value of l = 108
Therefore, sum of ASCII values = 108 + 108 = 216
which is a perfect cube 6 (6 * 6 * 6 = 216)
Input: str = “a”
Output: No
ASCII value of a = 97
Therefore, sum of ASCII values = 97
which is not a perfect cube
Algorithm
- For each character in the String, find out its ASCII value
- Calculate sum of ASCII values of all characters
- Check whether this sum is a perfect cube or not.
- If the sum is a perfect cube, then print “Yes” otherwise “No”
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPerfectCubeString(string str)
{
int sum = 0;
for ( int i = 0; i < str.length(); i++)
sum += ( int )str[i];
long double cr = round(cbrt(sum));
return (cr * cr * cr == sum);
}
int main()
{
string str = "ll" ;
if (isPerfectCubeString(str))
cout << "Yes" ;
else
cout << "No" ;
}
|
Java
import java.util.*;
class GFG{
static boolean isPerfectCubeString(String str)
{
int sum = 0 ;
for ( int i = 0 ; i < str.length(); i++)
sum += ( int )str.charAt(i);
double cr = Math.round(Math.cbrt(sum));
return (cr * cr * cr == sum);
}
public static void main(String[] args)
{
String str = "ll" ;
if (isPerfectCubeString(str))
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python3
from math import ceil
def isPerfectCubeString(str1):
sum = 0
for i in range ( len (str1)):
sum + = ord (str1[i])
cr = ceil(( sum ) * * ( 1 / 3 ))
return (cr * cr * cr = = sum )
str1 = "ll"
if (isPerfectCubeString(str1)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG{
static bool isPerfectCubeString(String str)
{
int sum = 0;
for ( int i = 0; i < str.Length; i++)
sum += ( int )str[i];
double cr = Math.Round(Math.Pow(sum, ( double ) 1 / 3));
return (cr * cr * cr == sum);
}
public static void Main(String[] args)
{
String str = "ll" ;
if (isPerfectCubeString(str))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
Javascript
<script>
function isPerfectCubeString(str)
{
var sum = 0;
for ( var i = 0; i < str.length; i++)
{
sum += str.charCodeAt(i);
}
var cr = Math.round(Math.cbrt(sum));
return cr * cr * cr == sum;
}
var str = "ll" ;
if (isPerfectCubeString(str))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time complexity: O(n) where n is the length of the given string
Auxiliary space: O(1)