最大の数を形成するために与えられた数を配置しますか?
ここでは、与えられた数を再配置することによって最大の数を生成する方法を見ていきます。 {45、74、23}が指定されているとすると、プログラムは最大数である744523を検出します。したがって、各桁は配置されません。ただし、整数が最大数になるように配置されます。
この問題を解決するために、文字列の並べ替えを使用します。ただし、比較ロジックは異なります。比較関数は、2つの数値aとbを取り、それらを連結してabとbaを形成します。それらの中でどちらが大きいか、それが考慮されます。
アルゴリズム
compareStrings(a、b)
begin ab := concatenate b with a ba := concatenate a with b compare ba with ab, then return 1 if ba is bigger, otherwise return 0 end getLargest(arr): begin sort the arr with the comparison logic using compareString() for each string s in arr, do print s done endを実行します。
例
#include<iostream>
#include <string>
#include &t;vector>
#include <algorithm>
using namespace std;
int stringCompare(string a, string b) {
string ab = a.append(b);
string ba = b.append(a);
return ab.compare(ba) > 0 ? 1: 0;
}
void getLargest(vector<string> arr) {
sort(arr.begin(), arr.end(), stringCompare); //sort the array
for (int i =0; i < arr.size() ; i++ )
cout << arr[i];
}
int main() {
vector<string> arr;
arr.push_back("45");
arr.push_back("74");
arr.push_back("23");
getLargest(arr);
} 出力
744523
-
指定された文字列のセットを使用して母音の数をカウントするPythonプログラム
この記事では、以下に示す問題ステートメントの解決策について学習します。 問題の説明 −文字列が与えられたので、与えられた文字列のセットを使用して母音の数を数える必要があります。 ここでは、文字列全体をトラバースして、各文字が母音であるかどうかを確認し、カウントをインクリメントします。 次に、以下の実装の概念を観察しましょう- 例 def vowel_count(str): count = 0 #string of vowels vowel = "aeiouAEIOU" &nbs
-
指定された文字列のsetを使用して母音の数をカウントするPythonプログラム
このプログラムでは、ユーザー入力文字列を指定します。この文字列の母音の数を数える必要があります。ここでは、Pythonでsetを使用します。 Setは、反復可能、変更可能で、重複する要素がない、順序付けされていないコレクションデータ型です。 例 Input : str1=pythonprogram Output : 3 アルゴリズム Step 1: First we use one counter variable which is used to count the vowels in the string. Step 2: Creating a set of vowels. Step