The program must accept an integer N and divide it into groups of equal size (of 2 or 3 or 4 etc). Then, the program should sum up these groups and print the result. If the number cannot be divided into groups of equal size, consider the largest group size possible.
Boundary Condition(s):
10 <= N <= 10^9
Input Format:
The first line contains the integer N.
Output Format:
A single line contains the result after summing the groups.
Example Input/Output 1:
Input:
5423
Output:
107
Explanation:
The number is divided into groups of two: 54 and 23. Their sum is 77.
N = input().strip()
group_size = 2 if len(N) % 2 == 0 else 3
groups = [int(N[i:i+group_size]) for i in range(0, len(N), group_size)]
print(sum(groups))
#include<stdio.h>
#include<string.h>
int main() {
char N[11];
scanf("%s", N);
int len = strlen(N);
int group_size = (len % 2 == 0) ? 2 : 3;
int sum = 0;
for(int i = 0; i < len; i += group_size) {
int group = 0;
for(int j = 0; j < group_size && i+j < len; j++) {
group = group * 10 + (N[i+j] - '0');
}
sum += group;
}
printf("%d", sum);
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char N[11];
cin >> N;
int len = strlen(N);
int group_size = (len % 2 == 0) ? 2 : 3;
int sum = 0;
for(int i = 0; i < len; i += group_size) {
int group = 0;
for(int j = 0; j < group_size && i+j < len; j++) {
group = group * 10 + (N[i+j] - '0');
}
sum += group;
}
cout << sum;
return 0;
}
import java.util.Scanner;
public class GroupAndSum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String N = sc.next();
int len = N.length();
int group_size = (len % 2 == 0) ? 2 : 3;
int sum = 0;
for(int i = 0; i < len; i += group_size) {
String group = N.substring(i, Math.min(i+group_size, len));
sum += Integer.parseInt(group);
}
System.out.println(sum);
}
}
Leave a Reply