fork download
  1. using System;
  2.  
  3. public class Nibble
  4. {
  5. const int bits = 4;
  6.  
  7. private bool[] _bools = new bool[bits];
  8.  
  9. public void Reset()
  10. {
  11. for ( int i = 0; i < _bools.Length; i++ )
  12. _bools[i] = false;
  13. }
  14.  
  15. public void Increment()
  16. {
  17. bool[] result = new bool[bits];
  18. bool[] carries = new bool[bits + 1];
  19.  
  20. carries[0] = true;
  21.  
  22. for ( int i = 0; i < bits; i++ )
  23. {
  24. result[i] = _bools[i] ^ carries[i];
  25. carries[i + 1] = _bools[i] && carries[i];
  26. }
  27.  
  28. if ( carries[bits] )
  29. Console.WriteLine("Overflow!");
  30.  
  31. _bools = result;
  32. }
  33.  
  34. public byte Value
  35. {
  36. get
  37. {
  38. byte result = 0;
  39. for ( int i = 0; i < bits; i++ )
  40. {
  41. if ( _bools[i] )
  42. result += (byte)(1 << i);
  43. }
  44. return result;
  45. }
  46. }
  47. }
  48.  
  49. static class Program
  50. {
  51. static void Main()
  52. {
  53. var nibble = new Nibble();
  54. for ( int i = 0; i < 17; i++ )
  55. {
  56. Console.WriteLine(nibble.Value);
  57. nibble.Increment();
  58. }
  59. }
  60. }
Success #stdin #stdout 0.03s 24120KB
stdin
Standard input is empty
stdout
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Overflow!
0