-7

This is the code(cpp)

    #include <iostream>
    #include <string>
    #include <numeric>//to import the accumulate function
    #include <vector>
    #include <algorithm>

    using namespace std;
    int main(){
    vector<long long> vi;
     string s; //this contains the long number its better not to type here
    int k=0,sum=0;
     for(int i=0;i<s.length();i++){
      k=(int)s[i]-(int)'0';
     cout<<k<<endl;
       vi.push_back(k);
 
      }
      for(int i:vi){
        cout<<i<<endl;
      }
         cout<<accumulate(vi.begin(),vi.end(),0);

    
        } 

whatever i do i get the answer 22660 i tried using without accumulate still 22660 ,i dont know why this happens

cs95
  • 379,657
  • 97
  • 704
  • 746
Vict_r prin_e
  • 11
  • 1
  • 1
  • 3

1 Answers1

0

I don't understand why you are using std::vector. You could calculate the sum without using the vector:

int k=0,sum=0;
for(int i=0;i<s.length();i++)
{
    k = s[i]-'0';
    sum += k;
}

Note: if you are a little paranoid of the sum value fitting into an integer, you can use an unsigned integer since digits can't be negative.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154