📜  程序来查找字符串中字符的ASCII值的乘积

📅  最后修改于: 2021-05-31 16:57:22             🧑  作者: Mango

给定一个字符串str。任务是找到字符串中字符的ASCII值的乘积。
例子

Input : str = "IS"
Output : 6059
73 * 83 = 6059

Input : str = "GfG"
Output : 514182

这个想法是从迭代字符串的字符开始,然后将它们的ASCII值乘以一个变量,即prod。因此,在字符串完全迭代之后返回prod
注意:如果字符串很大,则由于int的大小有限,程序可能会导致分段错误。
下面是上述方法的实现:

C++
// C++ program to find product
// of ASCII value of characters
// in string
 
#include 
using namespace std;
 
// Function to find product
// of ASCII value of characters
// in string
long long productAscii(string str)
{
    long long prod = 1;
 
    // Traverse string to find the product
    for (int i = 0; i < str.length(); i++) {
        prod *= (int)str[i];
    }
 
    // Return the product
    return prod;
}
 
// Driver code
int main()
{
    string str = "GfG";
 
    cout << productAscii(str);
 
    return 0;
}


Java
// Java program to find product
// of ASCII value of characters
// in string
class GFG
{
 
// Function to find product
// of ASCII value of characters
// in string
static long productAscii(String str)
{
    long prod = 1;
 
    // Traverse string to find the product
    for (int i = 0; i < str.length(); i++)
    {
        prod *= str.charAt(i);
    }
 
    // Return the product
    return prod;
}
 
// Driver Code
public static void main(String[] args)
{
    String str = "GfG";
     
    System.out.println(productAscii(str));
}
}
 
// This code is contributed by Bilal


Python3
# Python3 program to find product
# of ASCII value of characters
# in string
 
# Function to find product
# of ASCII value of characters
# in string
def productAscii(str):
 
    prod = 1
 
    # Traverse string to find the product
    for i in range(0, len(str)):
        prod = prod * ord(str[i])
 
    # Return the product
    return prod
 
# Driver code
if __name__=='__main__':
    str = "GfG"
 
    print(productAscii(str))
 
# This code is contributed by
# Sanjit_Prasad


C#
// C# program to find product
// of ASCII value of characters
// in string
using System;
 
class GFG
{
 
// Function to find product
// of ASCII value of characters
// in string
static long productAscii(String str)
{
    long prod = 1;
 
    // Traverse string to find the product
    for (int i = 0; i < str.Length; i++)
    {
        prod *= str[i];
    }
 
    // Return the product
    return prod;
}
 
// Driver Code
static public void Main ()
{
    String str = "GfG";
     
    Console.Write(productAscii(str));
}
}
 
// This code is contributed by Raj


PHP


Javascript


输出:
514182

时间复杂度: O(N),其中N是字符串的长度。

想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”