Advertisement
mjunolainen

AtoiBase

Jul 25th, 2021
345
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.34 KB | None | 0 0
  1. /*Write a program that takes a `string` number and its `string` base as arguments and prints its conversion as an `int`.
  2.  
  3. - If the base or the `string` number is not valid it returns `0`.
  4.  
  5. - If the number of arguments is bigger or lower that two it should print a newline `\n`.
  6.  
  7. Validity rules for a base :
  8.  
  9. - A base must contain at least 2 characters.
  10. - Each character of a base must be unique.
  11. - A base should not contain `+` or `-` characters.
  12.  
  13. Only valid `string` numbers will be tested.
  14.  
  15. The program **does not have** to manage negative numbers.*/
  16.  
  17. package atoibase
  18.  
  19. import (
  20.     "strings"
  21. )
  22.  
  23. func AtoiBase(s string, base string) int {
  24.  
  25.     indx := 0
  26.     for _, res := range base {
  27.         if string(res) == "-" || string(res) == "+" || strings.Count(base, string(res)) > 1 {
  28.             indx = 1
  29.             break
  30.         }
  31.     }
  32.     if indx == 1 || lent2(base) < 2 {
  33.         return 0
  34.     } else {
  35.         result := 0
  36.         for i, res := range s {
  37.             ind := strings.Index(base, string(res))
  38.             result += ind * RecursivePower(lent2(base), lent2(s)-1-i)
  39.         }
  40.         return result
  41.     }
  42. }
  43. func RecursivePower(nb, power int) int {
  44.     if power < 0 {
  45.         return 0
  46.     }
  47.     if power == 0 {
  48.         return 1
  49.     } else if power%2 == 0 {
  50.         return RecursivePower(nb, power/2) * RecursivePower(nb, power/2)
  51.     } else {
  52.         return nb * RecursivePower(nb, power/2) * RecursivePower(nb, power/2)
  53.     }
  54. }
  55. func lent2(d string) int {
  56.     inc := 0
  57.     for range d {
  58.         inc++
  59.     }
  60.     return inc
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement