gpt4 book ai didi

c++ - 我陷入了C++的这种语法中。 “Check if the frequency of all the digits in a number is same”

转载 作者:行者123 更新时间:2023-12-02 09:47:48 27 4
gpt4 key购买 nike

我在“检查数字中所有数字的频率是否相同”上练习编码问题

#include<bits/stdc++.h> 
using namespace std;

// returns true if the number
// passed as the argument
// is a balanced number.

bool isNumBalanced(int N)
{

string st = to_string(N);
bool isBalanced = true;

// frequency array to store
// the frequencies of all
// the digits of the number
int freq[10] = {0};
int i = 0;
int n = st.size();

for (i = 0; i < n; i++)

// store the frequency of
// the current digit
freq[st[i] - '0']++;

for (i = 0; i < 9; i++)
{

// if freq[i] is not
// equal to freq[i + 1] at
// any index 'i' then set
// isBalanced to false
if (freq[i] != freq[i + 1])
isBalanced = false;
}

// return true if
// the string is balanced
if (isBalanced)
return true;
else
return false;
}

// Driver code
int main()
{
int N = 1234567890;
bool flag = isNumBalanced(N);

if (flag)
cout << "YES";
else
cout << "NO";
}
但我听不懂这段代码:
//存储的频率
//当前数字
freq [st [i]-'0'] ++;
这部分实际如何工作并存储频率?
除了这行,我还能写些什么?

最佳答案

st是一个字符串,因此是char的序列。 st[i]是此字符串中的第i个字符。
字符实际上是0到256之间的正整数,因此您可以将它们用于数学运算,例如-。这些整数根据ASCII字母分配给字符。例如:char 0分配给48,char 7分配给55(注意:在下面,我使用x表示字符)。
它们的顺序使数学运算可能变得明智,如下所示:char 7和char 0正好相隔7个数字,因此0 + 7 = 48 + 7 = 55 = 7。因此:7-0 = 7。
因此,您可以根据数字获得freq数组中的位置,即0代表0或7代表7。++运算符就地将该值递增。

关于c++ - 我陷入了C++的这种语法中。 “Check if the frequency of all the digits in a number is same”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63866072/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com