public boolean isDivisibleBy3(int num)
{
//Find if a number is divisible by 3 without using / or % operator
int sum=0;
String strnum=(new Integer(num)).toString();
if(num<10){
sum=num;
}
while(strnum.length()>=2)
{
sum=0;
for(int i=0;i<strnum.length();i++)
{
sum=sum+ Integer.parseInt(strnum.substring(i,i+1));
}
if(sum>=10)
{
strnum=(new Integer(sum)).toString();
}
else
{
break;
}
}
if(sum==3 || sum==6 || sum==9)
{
return true;
}
else
{
return false;
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment