Digits That Remain Same After Squaring

The program must accept an integer N as the input. The task is to determine and print the digits in N that remain the same after squaring. If no such digit exists, the program should print -1.

Boundary Condition(s):
10 <= N <= 10^9

Input Format:
The first line contains the integer N.

Output Format:
A single line contains the digits in N that remain the same after squaring. If no such digit exists, print -1.

Example Input/Output 1:
Input:
149

Output:
1 4

Explanation:
The digits 1 and 4 remain the same when squared (1^2 = 1 and 4^2 = 16). The digit 9 becomes 81 when squared. Hence the output is 1 4.

Example Input/Output 2:
Input:
278

Output:
-1

Explanation:
No digit in 278 remains the same after squaring. Hence the output is -1.

N = input().strip()
digits_same_after_squaring = [d for d in N if int(d) ** 2 % 10 == int(d)]

print(" ".join(digits_same_after_squaring) if digits_same_after_squaring else "-1")
#include<stdio.h>
#include<stdbool.h>

int main() {
    int N, flag = false;
    scanf("%d", &N);

    while(N) {
        int digit = N % 10;
        if(digit * digit % 10 == digit) {
            printf("%d ", digit);
            flag = true;
        }
        N /= 10;
    }

    if(!flag) {
        printf("-1");
    }
    return 0;
}
#include <iostream>
using namespace std;

int main() {
    int N;
    bool flag = false;
    cin >> N;

    while(N) {
        int digit = N % 10;
        if(digit * digit % 10 == digit) {
            cout << digit << " ";
            flag = true;
        }
        N /= 10;
    }

    if(!flag) {
        cout << "-1";
    }
    return 0;
}
import java.util.Scanner;

public class SameAfterSquaring {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        boolean flag = false;

        while(N > 0) {
            int digit = N % 10;
            if(digit * digit % 10 == digit) {
                System.out.print(digit + " ");
                flag = true;
            }
            N /= 10;
        }

        if(!flag) {
            System.out.println("-1");
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

More posts. You may also be interested in.