Advertisement
Guest User

Untitled

a guest
Apr 1st, 2016
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.58 KB | None | 0 0
  1. using System;
  2. namespace ConsoleApplication12
  3. {
  4.     class Program
  5.     {
  6.         static void Main(string[] args)
  7.         {
  8.             /*
  9.                 We are given an integer number N(read from the console), a
  10.                 bit value v(read from the console as well) (v = 0 or 1) and a
  11.                 position P(read from the console). Write a sequence of operators
  12.                 (a few lines of C# code) that modifies N to hold the value v at the position P
  13.                 from the binary representation of N while preserving all other bits in N. Print the resulting
  14.                 number on the console.
  15.             */
  16.             long num = long.Parse(Console.ReadLine());
  17.             long pos = long.Parse(Console.ReadLine());
  18.             long bit = long.Parse(Console.ReadLine());
  19.             string binary = Convert.ToString(num, 2);
  20.             char[] binaryChars = new char[64];
  21.             int j = binary.Length - 1;
  22.             int posCount = 0;
  23.             for (long i = binaryChars.Length - 1; i >= 0; i--)
  24.             {
  25.                 if (j >= 0)
  26.                 {
  27.                     binaryChars[i] = binary[j];
  28.                     j--;
  29.                 }
  30.                 else
  31.                 {
  32.                     binaryChars[i] = '0';
  33.                 }
  34.  
  35.                 if (posCount == pos)
  36.                 {
  37.                     binaryChars[i] = (char)(bit + '0');
  38.                 }
  39.                 posCount++;
  40.             }
  41.             binary = new string(binaryChars);
  42.             Console.WriteLine(Convert.ToInt64(binary, 2));
  43.         }
  44.  
  45.  
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement