C++ Fragments divisible by 11














































C++ Fragments divisible by 11



Fragments divisible by 11

Write a program in C++ program such that numbers of occurrences in the range of [1,n] divisible by 11 is found.


NOTE-> input is given in strings and uses a function to solve the problem. 


Code:

#include <iostream>
#include <string>
using namespace std;
bool check(string str) 

    int n = str.length(),sum=0,t=0; 
    for(int i=0;i<n;++i){
   
t=(str[i]-'0');//character to int
i%2==0?sum+=t:sum-=t;//<condition>?<if true then>:<false then>
}
return (sum%11==0);

int main()
{
  string num;
  cout<<
"Enter a number: ";
  cin>>num;
  int count=0,n=num.length();
  for(int i=0;i<n;++i){
      for(int j=i+1;j<n;++j){
          string subNum=string(&num[i],&num[j+1]);
          if(check(subNum))
              ++count;
      }
  }
  cout<<count<<endl;
}



OUTPUT



Comments