[Solved] Number Challenge with Java, C++, Python

Number Challenge: Mike set off with great zeal to the “Kracker Jack Fun Fair 2017”. There were numerous activities in the fair, though Mike being a math expert, liked to participate in the Number Challenge.

Mike was given a string D of numbers containing only digits 0’s and 1’s. His challenge was to make the number to have all the digits same. For that, he should change exactly one digit, i.e. from 0 to 1 or from 1 to 0. If it is possible to make all digits equal (either all 0’s or all 1’s) by flipping exactly 1 digit then he has to output “Yes“, else print “No” (without quotes).

Write a program to help Mike win over his challenge.

Input Format:
First and only input contains a string D of numbers made of only digits 1’s and 0’s.

Output Format:
Output “Yes” or a “No“, depending on whether its possible to make it all 0s or 1s or not. 
Refer sample input and output for formatting specifications.

Sample Input1:
101
Sample Output1:
Yes

Sample Input2:
1100
Sample Output2:
No

Solution

import java.util.Scanner;
 class Main
{
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        String s=sc.nextLine();
        System.out.println(isSame(s)?"Yes":"No");
    }
    static boolean isSame(String s)
    {
        //sauravhathi
        int zero=0,one=0;
        for(int i=0;i<s.length();i++)
        {
            char c=s.charAt(i);
            if(c=='0')
            zero++;
            else
            one++;
        }
        return(zero==1 || one==1);
    }
}
#include <stdio.h>
#include <string.h>
int main()
{
    int sum = 0, i, l;
    char d[50];
    scanf("%s", d);
    //sauravhathi
    l = strlen(d);
    for (i = 0; i < l; i++)
        if (d[i] == '1')
            sum = sum + 1;
    if (sum == 1 || (sum == (l - 1)))
        printf("Yes");
    else
        printf("No");
    return 0;
    //sauravhathi
}
d = input()
l = len(d)
sum = 0
for i in range(0, l):
    if d[i] == '1':
        sum = sum + 1
if sum == 1 or (sum == (l - 1)):
    print("Yes")
else:
    print("No")

Happy Learning – If you require any further information, feel free to contact me.

Share your love
Saurav Hathi

Saurav Hathi

I'm currently studying Bachelor of Computer Science at Lovely Professional University in Punjab.

📌 Nodejs and Android 😎
📌 Java

Articles: 444

Leave a Reply

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