Advertisement
mustafov

Change Even Bits

Sep 3rd, 2015
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.23 KB | None | 0 0
  1. // Change Even Bits
  2. //You are given a number N and you have to read from the console exactly N + 1 integers and additionally an integer L – the number //to be processed. Your task is to count the bits in each of the N input integers (let this be the number len), then change bit to //"1" len even positions (0, 2, 4, …) of the input number L. Print on the console the obtained number and the total number of bits //that have actually been changed. To be counted as changed they should have been “0” at first and then changed to “1”. The //comments in the example below will help you understand better what you should do. Note that "0" consists of 1 bit (len=1).
  3.  
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9.  
  10. namespace ConsoleApplication2
  11. {
  12.     class Program
  13.     {
  14.         static void Main(string[] args)
  15.         {
  16.             int n = int.Parse(Console.ReadLine());
  17.  
  18.             int[] numbers = new int[n];
  19.             int[] counts = new int[n];
  20.  
  21.             int count = 0;
  22.  
  23.             int f = 0;
  24.             for (int i = 0; i < n; i++)
  25.             {
  26.                 int num = int.Parse(Console.ReadLine());
  27.                 string bin = Convert.ToString(num, 2);
  28.                 count = bin.Length;
  29.  
  30.                 numbers[f] = num;
  31.                 counts[f] = count;
  32.                 f++;
  33.             }
  34.             int bitCounts = 0;
  35.             int l = int.Parse(Console.ReadLine());
  36.             for (int k = 0; k < n; k++)
  37.             {
  38.                
  39.                 for (int j = 0; j < 2 * counts[k] - 1; j += 2)
  40.                 {
  41.                     int max = 2 * counts[k] - 1;
  42.                     if (max < counts[k])
  43.                     {
  44.                         max = counts[k];
  45.                     }
  46.                     string b = Convert.ToString(l, 2).PadRight(max, '0');
  47.                     int bitValue = l & (1 << j);
  48.                     if (bitValue == 0)
  49.                     {
  50.                         bitCounts++;
  51.                     }
  52.                     l = l | (1 << j);
  53.                 }
  54.                
  55.             }
  56.             Console.WriteLine(l);
  57.             Console.WriteLine(bitCounts);
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement