Given a number as the input, compute the new number by adding the square of each of its digits to the original number. If the input is not a valid number, print Invalid as the output.
Example Input/Output 1:
Input:
125
Output:
140
Explanation:
The squares of digits are 1, 4, and 25. Original number 125 + 1 + 4 + 25 = 140. Hence the output is 140.
Example Input/Output 2:
Input:
48
Output:
80
Explanation:
The squares of digits are 16 and 64. Original number 48 + 16 + 64 = 80. Hence the output is 80.
Example Input/Output 3:
Input:
97a
Output:
Invalid
#include<stdio.h>
#include<ctype.h>
int main() {
char str[1000];
scanf("%s", str);
int i = 0, sum = 0;
while(str[i]) {
if(isdigit(str[i])) {
sum += (str[i] - '0') * (str[i] - '0');
} else {
printf("Invalid");
return 0;
}
i++;
}
printf("%d", sum + atoi(str));
return 0;
}
s = input().strip()
if not s.isdigit():
print("Invalid")
else:
print(sum(int(ch) ** 2 for ch in s) + int(s))
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cin >> s;
int sum = 0;
for(char ch : s) {
if(!isdigit(ch)) {
cout << "Invalid";
return 0;
}
sum += (ch - '0') * (ch - '0');
}
cout << sum + stoi(s);
return 0;
}
import java.util.Scanner;
public class SquareDigitAddition {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
int sum = 0;
for(char ch : s.toCharArray()) {
if(!Character.isDigit(ch)) {
System.out.println("Invalid");
return;
}
int digit = ch - '0';
sum += digit * digit;
}
System.out.println(sum + Integer.parseInt(s));
}
}