Write a program that solves exercises 1.3 or 1.5. If you solve both correctly, 20 extra points will be given. For Exercise 1.3, you can use only the following C++ function or its Java equivalent to output the results of your program:
void printDigit(char c ){
if (c=='-' || c=='+' || c=='.' || c == '\n' ||
(c>='0' && c<='9')){
cout << c;
return;
}
cout << "Invalid characters." <<
endl;
return;
}
Exercise 1.3
Write a function to output an arbitrary double number (which might be negative) using only printDigit for I/O.
Exercise 1.5
Write a recursive function that returns the number of 1 in the binary representation of N . Use the fact that this is equal to the number of 1 in the representation of N/ 2, plus 1, if N is odd.
exercise 1.3:
public class Exercice_1_3 {
public static void main(String[] args) {
printOut(1329);
}
// Recursive method that prints a positive integer
one character at a time
public static void printOut(int n) {
if (n>= 10) {
printOut(n /
10);
}
printDigit(n % 10);
}
public static void printDigit(int n) {
if (0 <= n
&& n <= 9) {
System.out.print(n);
}
}
}
exercise 1.5:
/* Function to get no of set bits in binary
representation of passed binary no. */
unsigned int countSetBits(unsigned int n)
{
unsigned int count = 0;
while(n)
{
count += n & 1;
n >>= 1;
}
return count;
}
/* Program to test function countSetBits */
int main()
{
int i = 9;
printf("%d", countSetBits(i));
getchar();
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.