用數字字串檢查能否形成電話號碼的 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;
}

輸入

"5818005553985"

輸出

1

更新日期:2022 年 3 月 11 日

847 次瀏覽

職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.