用数字字符串检查能否形成电话号码的 C++ 代码
假设我们有一个包含 n 个数字的字符串 S。一个恰好有 11 位数字的号码如果以 '8' 开头,即为电话号码。在一个操作中,我们可以从 S 中删除一个数字。我们必须检查字符串是否可以构成有效的电话号码。
因此,如果输入看起来像 S = "5818005553985",那么输出将为真,因为我们可以用 11 个字符构成字符串 "8005553985",并且第一个数字是 8。
步骤
为了解决这个问题,我们将遵循以下步骤 −
m := size of S insert '8' at the end of S if if location of 8 <= (m - 11), then: return true return false
示例
让我们看看下面的实现以获得更好的理解 −
#include <bits/stdc++.h> using namespace std; bool solve(string S){ int m = S.size(); S.push_back('8'); if ((int(S.find('8')) <= (m - 11))) return true; return false; } int main(){ string S = "5818005553985"; cout << solve(S) << endl; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输入
"5818005553985"
输出
1
广告