さらに続き晒す

10章(プリプロセッサ)は解く気にならなかったのでスルー。実用上は気にしなくて大丈夫っしょ…

9章 9-1

ただのwc

#include <iostream>
#include <string>

int main(){
	std::string target; // string to be counted
	int my_wc(std::string str);
	target = "This is target string. asdf fdsa";
	
	std::cout << "target string has " << my_wc(target) << " words.\n";
}

int my_wc(std::string str){
	int words;
	int counter;
	counter = 0;
	words = 1;
	while(counter < str.length()){
		if(str.at(counter) == ' ') {
			words++;	
		}
		counter++;
	}
	return words;
}

9章 9-4

文字列から文字の値を合計してハッシュ値とする

#include <iostream>
#include <string>

int main(){
	std::string target = "AsDFFDsA0";
	int make_hashcode(std::string str);
	
	std::cout << "hashcode of string \"" << target << "\" is " << make_hashcode(target) << "\n";
}

int make_hashcode(std::string str){
	int i;
	int value;
	i = 0;
	value = 0;
	while(i < str.length()){
		value += static_cast<int>(str.at(i));
		i++;
	}
	return value;
}

11章 11-4

最初の3問は作業ゲーすぎて解く気にならず。これはあるint値のbit数カウント。16bitを仮定。

#include <iostream>

int main(){
  int target;
  int count(int i);
  std::cout << "Enter a number: ";
  std::cin >> target;
  std::cout << "1s in binary of " << target << ": " << count(target) << "\n";
}

int count(int i){
  int bits;
  int bit;
  bits = 0;
  for(bit = 0x8000; bit > 0; bit = (bit >> 1)){
    if((i & bit) > 0){
      bits++;
    }
  }
  return bits;
}

11章 11-6

立っている1を左に寄せる。11-5(4桁ごとにbitを区切る)を使用してのコード。

#include <iostream>

int main(){
  int target;
  long int lshift_all(long int target);
  std::string split_bits(long int target);
  std::cout << "Enter a number: ";
  std::cin >> target;
  std::cout << "originally: " << split_bits(target) << "\n";
  std::cout << "shifted to left: " << split_bits(lshift_all(target)) << "\n";
}

long int lshift_all(long int target){
  long int new_int = 0;
  int bits = 0;
  int i;
  for(i = 31; i >= 0; i--){
    if((target & (1 << i)) > 0){
      new_int |= 1 << (31 - bits);
      bits++;
    }
  }
  return new_int;
}

std::string split_bits(long int target){
  long int bit;
  int i;
  std::string return_string;
  return_string = "";
  i = 0;
  for(bit = 0x80000000; bit > 0; bit = (bit >> 1)){
    // write bits
    if((target & bit) > 0){
      return_string += "1";
    } else {
      return_string += "0";
    }
    i++;
    if(i % 4 == 0 && i != 32){
      return_string += " ";
    }
  }
  return return_string;
}