tam.tony
BAN USERI assume the integers could be very large, ie > 64 so th so didn't think bitwise would work.
#!/usr/bin/perl -w
use strict;
my @int = (4,7,2,2,5,3,5,7,7,3,4,5);
my %seen = ();
print "array is ", join(",", @int),"\n";
for (my $i = 0; $i <= $#int; $i++) {
if (!defined($seen{$int[$i]})) {
$seen{$int[$i]} = 1;
} else {
$seen{$int[$i]}++;
}
}
print "odd count is :\n";
foreach my $key (keys(%seen)) {
if ($seen{$key} && ($seen{$key} % 2) == 1) {
print $key, " = ", $seen{$key},"\n";
}
}
./oddArray.pl
array is 4,7,2,2,5,3,5,7,7,3,4,5
odd count is :
5 = 3
7 = 3
!cc
cc sumBinary.c
./a.out
0111101 + 1101 = 1001010
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// convert from string binary to integer
int atob(char *a) {
int n = strlen(a);
int num = 0;
int index = 0;
while (n-- >= 0) {
if (a[n] == '1') {
num = num + (1 << index);
}
index++;
}
return num;
}
// convert an int to string
// the caller needs to delete the memory return
char *itobs(int myInt) {
char *c = malloc(sizeof (char) * 33);
int seenOne = 0;
int cur = 0;
for (int i = 0; i < 32; i++) {
if (myInt & (1 << (31 - i))) {
c[cur++] = '1';
seenOne = 1;
} else {
if (seenOne == 1) {
c[cur++] = '0';
}
}
}
c[cur] = '\0';
return c;
}
char *sumBinary(char *a, char *b) {
return itobs(atob(a) + atob(b));
}
int
main (int arc, char *argv[]) {
printf( "0111101 + 1101 = %s\n", sumBinary("0111101", "1101"));
}
what if an integer value exceed the size of an int, xor wouldn't work in that case?
- tam.tony April 25, 2015int arr[] = { 99999, 99999 };