给定一个由“I”和“D”组成的序列,其中“I”表示递增序列,“D”表示递减序列。编写一个程序,对给定的序列进行解码以构造没有重复数字的最小数。
数字应从 1 开始,即不应有零。
Input: D Output: 21 Input: I Output: 12 Input: DD Output: 321 Input: II Output: 123 Input: DIDI Output: 21435 Input: IIDDD Output: 126543 Input: DDIDDIID Output: 321654798
My python code works. I translated it into C++ but the C++ version doesn't work. I don't understand why.
Python code (Works):
s = input()
ans = [1]
count = 0
for i in s:
if i == 'I':
count = 0
k = len(ans)
ans.append(k + 1)
else:
count += 1
tmp = ans[-1]
for i in range(-1, -1 - count, -1):
ans[i] += 1
ans.append(tmp)
for i in ans:
print(i, end = "")
C++ 代码(不起作用,即没有给出正确的输出)#include <bits/stdc++.h>
using namespace std;
vector<int> digits(string s){
vector<int> ans = {1};
int count = 0;
for (char const &c : s){
if (c == 'I'){
count = 0;
int k = ans.size();
ans.push_back(k + 1);
}
else{
count ++;
int tmp = ans.back();
for (int i = ans.size() - 1; i > ans.size() - 1 - count; i--){
ans[i] += 1;
}
ans.push_back(tmp);
}
}
return ans;
}
int main(){
string s;
cin >> s;
vector<int> ans = digits(s);
for (int i = 0; i < ans.size(); i++){
cout << ans[i];
}
return 0;
}
例如 - 当我在 C++ 代码中输入 DD 时,它给出了 111,但它应该输出 321。
最佳答案
ans.size()
在 C++ 中返回 size_t
,它是无符号的(32 位或 64 位取决于您的配置)。您可以简单地投 ans.size()
到 int
解决您的问题,如下所示:
for ( int i = static_cast<int>(ans.size()) - 1; i > static_cast<int>(ans.size()) - 1 - count; i-- )
使用调试器,您可以检查您是否真正进入过 for-loop
的 body ,供您输入。正如 NotAProgrammer 所指出的,无符号到有符号转换可能是实现定义的,但这应该适用于您的示例的大多数(所有?)情况。
来自
[conv.integral]/3
:If the destination type is signed, the value is unchanged if it can be represented in the destination type; otherwise, the value is implementation-defined.
关于python - 从给定的 I 和 D 序列中形成最小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62899321/