Debug Error -Abort() Has Been Called

前端 未结 3 1013
难免孤独
难免孤独 2021-02-13 13:33

I\'m trying to enter a number,n and get the least super lucky number that is more than or equal to n. Super lucky: it\'s decimal representation contains equal amount of digits

3条回答
  •  有刺的猬
    2021-02-13 13:48

    There are couple of issues:

    1. When you call superLucky from main, s is empty. stoi(s) throws an exception when s is empty.

    2. The check s.size() > 10 is not robust. It is platform dependent. You can use a try/catch block to deal with it instead of hard coding a size.

    Here's a more robust version of the function.

    void superLucky(int n,string s, int count4, int count7)
    {
       int d = 0;
       if ( s.size() > 0 )
       {
          try
          {
             d = stoi(s);
          }
          catch (...)
          {
             return;
          }
    
          if (( d >= n ) && (count4 == count7) && (count4+count7)!=0)
          {
             cout << s << endl;
             return;
          }
       }
    
       superLucky(n, s + '7',count4,count7+1);
       superLucky(n, s + '4', count4+1, count7);
    }
    

提交回复
热议问题