Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » What could be the purpose of taking N integers as string.

This thread is locked; no one can reply to it. rss feed Print
What could be the purpose of taking N integers as string.
Doctor Cop
Member #16,833
April 2018
avatar

#SelectExpand
1#include<iostream> 2using namespace std; 3int main(){ 4 int T; 5 cin>>T; 6 for(int a=1;a<=T;a++){ 7 int result =0; 8 string s; 9 cin>>s; 10 int n=s.size(); 11 for(int i=0;i<n;i++){ 12 result =result +s[i]; 13 } 14 if(result%3==0){ 15 cout<<"Yes"<<endl; 16 } 17 if(result%3!=0){ 18 cout<<"No"<<endl; 19 } 20 } 21 return 0; 22}

This is the code I found in the submissions after trying four time in a row with my simple logic.

This is something I am unable to wrap my head around, that much I know that my logic didn't work because the inputs were very large but how is this code not having any problems with size limit?

This is the problem:-

#SelectExpand
1You are given a number N you need to check if it is divisible 3. 2 3Input: 4 5The first line of the input contains an integer T, denoting number of test cases. Each of the next T lines contains an integer N. 6 7Output: 8 9For each of the test cases print "Yes" if N is divisible by 3 else "No". 10 11Constraints: 12 131<=T<=10^3 14 151<=N<=10^1000

GullRaDriel
Member #3,861
September 2003
avatar

This will overflow like any other.
Particularly here:

result =result +s[i];

Edit:
Maybe this example would help : https://www.w3resource.com/cpp-exercises/basic/cpp-basic-exercise-8.php

"Code is like shit - it only smells if it is not yours"
Allegro Wiki, full of examples and articles !!

Peter Hull
Member #1,136
March 2001

This is taking account of the divisibility rule - you just need to add the digits and check that's divisible by 3. Since the number has 100 digits or less there's no risk its sum of digits will overflow.

Really result =result +s[i] should be result = result + s[i] - '0' but I think it won't matter because the ASCII code for '0' is itself divisible by 3 (48 is it?)

GullRaDriel
Member #3,861
September 2003
avatar

In the given example there can be an overflow because T is not capped like Peter said, and like the constraint was asking.

"Code is like shit - it only smells if it is not yours"
Allegro Wiki, full of examples and articles !!

Audric
Member #907
January 2001

These problems give the 'constraints from the outside', in order to plan for worst case scenario.
It doesn't mean you have to specifically test for these conditions and immediately fail/abort as soon they're exceeded.
So using uint16 for N or result WOULD have been a fault, but int is well enough to work.

Go to: