Adobe Interview Question
Member Technical StaffsCountry: India
Interview Type: In-Person
void multiple0f3()
{
int previousmod=0;
int curmod=0;
char ch;
bool test[100]; //Assuming max of 100 digits
int k=0;
cin>>ch;
while(ch!='e')
{
int d=ch-'0';
curmod=d%3;
previousmod=(curmod+previousmod)%3;
if(previousmod==0)
test[k++]=true;
else
test[k++]=false;
cin>>ch;
}
cout<<endl;
for(int i=0;i<k;i++)
cout<<test[i]<<endl;
}
as the numbers are coming in, we can keep doing processing on these numbers by adding as the number comes and % the sum with 3, so the resultant output will be 0,1,2 we add this output with the next number coming in the stream and again % the sum by 3.
But this has the disadvantage of operating all the times even when not asked/required.
import java.util.Scanner;
public class divby3 {
public static void main (String args[])
{
int sum=0;
int i = 1;
while (i==1)
{
Scanner in =new Scanner(System.in);
String digit=in.next();
int number=Integer.parseInt(digit);
sum=sum+number;
System.out.println(sum);
if (sum%3==0)
{
System.out.println("Divisible by 3");
}
else
{
System.out.println("Not divisibe by 3");
}
System.out.print("You want to continue?");
String response=in.next();
i=Integer.parseInt(response);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Mod3
{
class Program
{
static void Main(string[] args)
{
int[] arr=new int[10];
int i,sum=0;
char ch='y';
for(i=0;i<10;i++)
{
Console.WriteLine("Enter the digit");
arr[i] = Convert.ToInt32(Console.ReadLine());
sum = sum + arr[i];
Console.WriteLine(sum);
Console.WriteLine("Do you want to continue (Y/N) :");
ch = Convert.ToChar(Console.ReadLine());
switch (ch)
{
case 'y':
case 'Y':
continue;
case 'n':
case 'N':
if (sum % 3 == 0)
{
Console.WriteLine("Divisble by 3");
break;
}
else
{
Console.WriteLine("Not divisible by 3");
break;
}
default:
Console.WriteLine("Enter the correct value");
break;
}
}
}
}
}
package test;
import java.io.DataInputStream;
import java.io.IOException;
public class MultipleOf3 {
public static void main(String [] args)
{
int in;
DataInputStream br=new DataInputStream(System.in);
try {
int sum=0;
while((in=br.read())!='a')
{
Character c=(char)in;
int i = 0;
if(c<='9'&&c>='0')
{
i=Integer.parseInt(c.toString());
sum+=i;
System.out.print(i);
if(sum%3==0)
{
break;
}
}
}
System.out.println();
System.out.println("div by 3!!!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Take the sum and check for divisiblity by 3.
- Anonymous June 27, 2014So maintain running sum (mod 3, to cater to overflows) and check if sum is 0 when stream ends.
It does not matter whether you get the most significant digit first.
This assumes base 10.