Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Write a program that takes a `string` number and its `string` base as arguments and prints its conversion as an `int`.
- - If the base or the `string` number is not valid it returns `0`.
- - If the number of arguments is bigger or lower that two it should print a newline `\n`.
- Validity rules for a base :
- - A base must contain at least 2 characters.
- - Each character of a base must be unique.
- - A base should not contain `+` or `-` characters.
- Only valid `string` numbers will be tested.
- The program **does not have** to manage negative numbers.*/
- package atoibase
- import (
- "strings"
- )
- func AtoiBase(s string, base string) int {
- indx := 0
- for _, res := range base {
- if string(res) == "-" || string(res) == "+" || strings.Count(base, string(res)) > 1 {
- indx = 1
- break
- }
- }
- if indx == 1 || lent2(base) < 2 {
- return 0
- } else {
- result := 0
- for i, res := range s {
- ind := strings.Index(base, string(res))
- result += ind * RecursivePower(lent2(base), lent2(s)-1-i)
- }
- return result
- }
- }
- func RecursivePower(nb, power int) int {
- if power < 0 {
- return 0
- }
- if power == 0 {
- return 1
- } else if power%2 == 0 {
- return RecursivePower(nb, power/2) * RecursivePower(nb, power/2)
- } else {
- return nb * RecursivePower(nb, power/2) * RecursivePower(nb, power/2)
- }
- }
- func lent2(d string) int {
- inc := 0
- for range d {
- inc++
- }
- return inc
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement